Understanding Relationships & Foreign Keys in Mongoose - mongodb

In MongoDB/Mongoose, how do I define a relationship? I think there are a few ways I've seen, but I'm not sure I understand the differences or when do I use which. I am using Mongoose 3
I've defined Todo and TodoList model, where the relationship is obvious. So following the docs http://mongoosejs.com/docs/documents.html, I've defined classes like:
# Todo.coffee
mongoose = require "mongoose"
todoSchema = mongoose.Schema
name: String
desc: String
dueOn: Date
completedOn: Date
module.exports = mongoose.model "Todo", todoSchema
# TodoList.coffee
mongoose = require "mongoose"
Todo = require "./Todo"
todoListSchema = mongoose.Schema
name: String
todos: [Todo.schema]
module.exports = mongoose.model "TodoList", todoListSchema
Then I tried testing the classes:
list = new TodoList
name: "List 1"
todos: [
{ name: "Todo 1", desc: "Hello", dueOn: new Date(2012,10,1), completedOn: new Date(2012,10,2) }
{ name: "Todo 2" }
{ name: "Todo 3", desc: "Hello 2", dueOn: new Date(2012,10,6), completedOn: new Date(2012,10,2) }
{ name: "Todo 4" }
]
#list.todos.push { name: "Todo 5" }
console.log "List", list
list.save (err) ->
if !err
TodoList.find {}, (err, lists) ->
console.log "TODOS"
console.log lists.length, lists
done(err)
else
console.log "ERROR!!!"
done err
When I try to do Todo.find() I get nothing, so the Model (Todo.coffee) is kind of redundant? It looks like Todo are stored in TodoList, as a user I may not care, but I wonder what are the implications? Eg. will the document get too large? 1 TodoList with too many Todos? Does that matter? What if I allow nested Todos (not that I want to do itm just for understanding), is it better to store documents separately then? How do I do that, if I so desire, and when do I do it?
I saw another method, in Mongoose 2 actually. I don't know, if it is possible in 3. Something like using ObjectId instead of nested docs. Maybe thats to store it separately?

I'm still new to Node, Mongoose, and Mongo, but I think I can address at least part of your question. :)
Your current method is the same as I tried doing at first. Basically, it ends up storing it very similarly to this (written in JS, since I don't know CoffeeScript):
var todoListSchema = new mongoose.Schema({
name: String,
todos: [{
name: String,
desc: String,
dueOn: Date,
completedOn: Date
}]
});
I later found this method, which is what I was looking for, and I think what you were intending:
var todoListSchema = new mongoose.Schema({
name: String,
todos: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Todo' //Edit: I'd put the schema. Silly me.
}]
});
This stores an array of ObjectIds, which you can then load using Query#populate in Mongoose.
I don't know of the technical implications, but it makes more sense in my brain if I keep them separate, so that's what I'm doing. :)
Edit: Here is a some official docs that might be useful: http://mongoosejs.com/docs/populate.html

Related

Mongoose product category design?

I would like to create an eCommerce type of database where I have products and categories for the products using Mongodb and Mongoose. I am thinking of having two collections, one for products and one for categories. After digging online, I think the category should be as such:
var categorySchema = {
_id: { type: String },
parent: {
type: String,
ref: 'Category'
},
ancestors: [{
type: String,
ref: 'Category'
}]
};
I would like to be able to find all the products by category. For example "find all phones." However, the categories may be renamed, updated, etc. What is the best way to implement the product collection? In SQL, a product would contain a foreign key to a category.
A code sample of inserting and finding a document would be much appreciated!
Why not keep it simple and do something like the following?
var product_Schema = {
phones:[{
price:Number,
Name:String,
}],
TV:[{
price:Number,
Name:String
}]
};
Then using projections you could easily return the products for a given key. For example:
db.collection.find({},{TV:1,_id:0},function(err,data){
if (!err) {console.log(data)}
})
Of course the correct schema design will be dependent on how you plan on querying/inserting/updating data, but with mongo keeping things simple usually pays off.

Merging two Mongoose query results, without turning them into JSON

I have two Mongoose model schemas setup so that the child documents reference the parent documents, as opposed to the Parent documents having an array of Children documents. (Its like this due to the 16MB size limit restriction on documents, I didnt want to limit the amount of relationships between Parent/Child docs):
// Parent Model Schema
const parentSchema = new Schema({
name: Schema.Types.String
})
// Child Model Schema
const childSchema = new Schema({
name: Schema.Types.String,
_partition: {
type: Schema.Types.ObjectId,
ref: 'Parent'
}
})
I want to create a static method that I can query for a Parent document, then query for any Child documents that match the parent document, then create a new item in the parent document that will reference the Children array.
Basically if the Parent document is:
{
_id: ObjectId('56ba258a98f0767514d0ee0b'),
name: 'Foo'
}
And the child documents are:
[
{
_id: ObjectId('56b9b6a86ea3a0d012bdd062'),
name: 'Name A',
_partition: ObjectId('56ba258a98f0767514d0ee0b')
},{
_id: ObjectId('56ba7e9820accb40239baedf'),
name: 'Name B',
_partition: ObjectId('56ba258a98f0767514d0ee0b')
}
]
Then id be looking to have something like:
{
_id: ObjectId('56ba258a98f0767514d0ee0b'),
name: 'Foo',
children: [
{
_id: ObjectId('56b9b6a86ea3a0d012bdd062'),
name: 'Name A',
_partition: ObjectId('56ba258a98f0767514d0ee0b')
},{
_id: ObjectId('56ba7e9820accb40239baedf'),
name: 'Name B',
_partition: ObjectId('56ba258a98f0767514d0ee0b')
}
]
}
Also, I want them to remain Mongoose documents, so I can update the Parents and Assets if I need to.
I was able to accomplish this by using toJSON on the Parent, then creating a new item that would hold the Child docs, but then obviously the Parent document isn't a real document..
The error I kept getting when I tried this was that I couldnt create a new element in the Document that wasnt in the schema.
I know I could do something like create a Virtual item that would return the promise that would query the Children, but im looking to have one static method, that returns one response (meaning they dont have to handle the virtual item as a promise or callback)
Let me know if this is possible. Thanks!
FYI, this apparently isn't possible, I've tried a few things and it doesn't seem like it will work.
Use the .populate() method of the schema.
Parent.find(query)
.populate("children")
.exec((err, items) => {
if (err) {
...
}
...
});

Mongoose populate() returning empty array

so I've been at it for like 4 hours, read the documentation several times, and still couldn't figure out my problem. I'm trying to do a simple populate() to my model.
I have a User model and Store model. The User has a favoriteStores array which contains the _id of stores. What I'm looking for is that this array will be populated with the Store details.
user.model
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
username: String,
name: {first: String, last: String},
favoriteStores: [{type: Schema.Types.ObjectId, ref: 'Store'}],
modifiedOn: {type: Date, default: Date.now},
createdOn: Date,
lastLogin: Date
});
UserSchema.statics.getFavoriteStores = function (userId, callback) {
this
.findById(userId)
.populate('favoriteStores')
.exec(function (err, stores) {
callback(err, stores);
});
}
And another file:
store.model
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var StoreSchema = new Schema({
name: String,
route: String,
tagline: String,
logo: String
});
module.exports = mongoose.model('Store', StoreSchema);
After running this what I get is:
{
"_id": "556dc40b44f14c0c252c5604",
"username": "adiv.rulez",
"__v": 0,
"modifiedOn": "2015-06-02T14:56:11.074Z",
"favoriteStores": [],
"name": {
"first": "Adiv",
"last": "Ohayon"
}
}
The favoriteStores is empty, even though when I just do a get of the stores without the populate it does display the _id of the store.
Any help is greatly appreciated! Thanks ;)
UPDATE
After using the deepPopulate plugin it magically fixed it. I guess the problem was with the nesting of the userSchema. Still not sure what the problem was exactly, but at least it's fixed.
I think this issue happens when schemas are defined across multiple files. To solve this, try call populate this way:
.populate({path: 'favoriteStores', model: 'Store'})

Does using dbref do anything more than just storing an `id`

My Mongoose schema:
// set up the schema
var CategorySubSchema = new Schema({
name: { type: String },
_category_main : { type: String, ref: 'CategoryMain' }
},
And my controller code:
CategorySub.create({
name : req.body.name,
_category_main : req.body.category_main
}, function(err, data){
An entry in my db:
{
"_id": "54dd163434d78ae58f6b1a69",
"name": "Snacks",
"_category_main": "54dcf4a71dfecb4d86ddcb87",
"__v": 0
},
So I used an underscore, because I was following an example. Does this mean anything to the database or is it just convention for references?
Also, instead of passing the entire JSON object in the request - req.body.category_main, why not just pass and id and change my schema to this?:
var CategorySubSchema = new Schema({
name: { type: String },
category_main_id : { type: String }
},
In short, Yes.
The below schema definition is an example of Manual references.
var CategorySubSchema = new Schema({
name: { type: String },
category_main_id : { type: String }
}
where,
you save the _id field of one document in another document as a
reference. Then your application can run a second query to return the
related data. These references are simple and sufficient for most use
cases.
In this case, we need to write explicit application code to fetch the referred document and resolve the reference. Since the driver that we use wouldn't know about the collection in which the referred document is present nor the database in which the referred document is present.
When you define the schema as below, this is an example of storing the details of the referred document .(Database references)
var CategorySubSchema = new Schema({
name: { type: String },
_category_main : { type: String, ref: 'CategoryMain' }
}
They include the name of the collection, and in some cases the
database name, in addition to the value from the _id field.
These details allow various drivers to resolve the references by themselves, since the name of the collection and the database(optional) of the referred document would be contained in the document itself, rather than we writing explicit application code to resolve the references.
So I used an underscore, because I was following an example. Does this mean anything to the database or is it just convention for
references?
Using underscore in the _id field is a valid naming convention, but mongoDb doesn't explicitly mention about the naming convention of other fields which are used to resolve references. You could just use any other field name as long as it conforms to this.

Mongoose Reference for simple code reference values?

I'm designing a MongoDB schema to save a fairly large/nested document. I'm planning on embedding as much as possible into a single document, but wasn't sure what to do with code/lookup values. For example, if we have a code table representing "priority", with the possible values being:
low
medium
high
Is this something I should use a Mongoose reference for, and create a simple document to hold priority, eg something like:
var PrioritySchema = new Schema({
description: String
});
This would then be referenced with something like the following:
var AnotherSchema = new Schema({
name: String,
active: Boolean,
priority: { type: String, ref: 'Priority' }
});
Or is this overkill? The thing I want to avoid is directly storing these "descriptions" in the main/overall model, then having a requirement change sometime in the future. For example, someone decides that instead of "medium", we need to call it "somewhat". In that situation, I assume I'd be stuck doing some sort of data migration?
you can do this :
var PrioritySchema = new Schema({
description: String
});
and this
var AnotherSchema = new Schema({
name: String,
active: Boolean,
priority: { PrioritySchema }
});
But if you want what you described further I would advise you to do this instead :
var AnotherSchema = new Schema({
name: String,
active: Boolean,
priority: { type: Schema.Types.ObjectId, ref: 'Priority' } // see this : Schema.Types.ObjectId != String
});
Let's make it simple if you need those values to be cross-documents you need to use reference. If the values are only existing because of the parent document then you can choose embing.
For more information read this :
http://mongoosejs.com/docs/2.7.x/docs/embedded-documents.html
FYI : I used to struggle a lot with this. If you follow the path of embing all nested sub-document you will face a lot of "What Why I can't do that :'(. At the end I choosed the referencing way I felt more confortable with it. embing != referencing.