Wednesday 15 June 2011

node.js - Mongoose – linking objects to each other without duplicating -


I have a model "category" There are many objects in the collection categories I have a model " The post "is the collection post can contain many objects with the posts of the user" post "object may be related to 1+ categories. "Post" Object to "Category" - How to link "Post" object without the subject of the "post" object as a sub-document? Of course, I should have the option to find all the posts related to certain categories.

I can think that in one way in all those categories the "post" object is to be stored in obj_id which is related to it. Depth in this way:

  var postSchema = mongoose.Schema ({title: string, description: string, category: [object], created time: number,})  < / Pre> 

and add category later ...

  post.category.push (obj_id);   

But is it really a Mongoose-it? Which way is right? Thank you.

P.S. I have also read about the methods of population in Mongoose docks, can it be useful in my case? It is not clear at all what it is.

This is a better tool for you, because you have many sub- Documents are appropriate when they are specifically for the original object To use the context, you must change your post-schema:

  var postSchema = mongoose.Schema ({title: string , Description: String, Category: [{type: Schema.Types.ObjectId, Reference: 'Category'}], Created Time: Number,});   

You can add categories by pushing documents on the array:

  post.category.push (category1); Post.save (callback);   

Then re-enter them during the query using the populate:

  Post.findOne ({title: 'test'}). Populate ('category') .exec (function (mistake, post) {if (error) returns handler error; console.log (post.category);});    

No comments:

Post a Comment