oehman
oehman

Reputation: 249

Creating relationships in MongoDB using Mongoose (in Node.js)

I have tried to find any similiar issues here on Stackoverflow without any luck. I am struggling to find the proper way to create a relationship between two documents. It is a very simple case of hierarchical categories. Each category can have ONE parent and multiple children.

var categorySchema = Schema({
    name: String,
    parent: { type: Schema.ObjectId, ref: 'Category' },
    children: [{ type: Schema.ObjectId, ref: 'Category' }],
    order: Number
});

var Category = mongoose.model('Category', categorySchema);

When I create a new Category I get the _id to the (if any) parent it should have. I get this _id as a String from a POST/PUT request and fetch the Category using this _id. The fetch works fine and I get the right Category as a result. But this is where I struggle, how do I use the returned result from the mongoose query to create the relationship between the new Category and its Parent?

var query = Category.find({'_id': parentCategoryID});
query.select('name');
query.exec(function (err, parentCategory) {
    if (!err) {
        console.log("Fetched parentCategory: "+parentCategory+".. parentCategory._id: "+parentCategory._id);
        var parent = parentCategory.toObject();
        var category = new Category();
        category.name = name;
        category.parent = Schema.ObjectId(parent._id);

console.log Fetched parentCategory: { name: 'Parent Category', _id: 5218dcd6e6887dae40000002 }.. parentCategory._id: undefined

I have tried setting the parent attribute in a multiple different ways and I cannot get it to work. Haven't had any luck finding documentation on the issue either.

Very thankful for ANY help in the matter and I hope more people can benefit from any answer to this question.

Upvotes: 2

Views: 4445

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146064

//problem 1: `find` returns a list of results. You just need findById
var query = Category.findById(parentCategoryID);
query.select('name');
query.exec(function (err, parentCategory) {
  //Problem 2: don't ignore errors. Handle them first and short-circuit return
    if (err) {
      console.err(err);
      return;
    }
    console.log("Fetched parentCategory: "+parentCategory+".. parentCategory._id: "+parentCategory._id);
    //problem 3: mongoose will do the right thing with your schema here
    //all you need is
    var category = new Category();
    category.name = name;
    category.parent = parentCategory;
    //and don't forget
    category.save(...callback....);
}

Also note if you have a schema, and you assign something that does not match the schema, mongoose will just drop the data, which is probably what was happening to you, assuming you called category.save() at some point.

Upvotes: 1

Related Questions