Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Add document to an embedded document array

Add document to an embedded document array

Problem

I'm trying to add an Embedded Document to an existing document field. I found one fitting answer with the search but I'm running into errors. I'm using node.js, Express and Mongoose.

My database schemas:

var entry = new Schema({
    name        : { type : String, required : true},
    description : { type : String, default: ""},
});

var compo = new Schema({
    name        : String,
    description : String,
    entries     : [entry]
});

And I'm trying to update the entries array with the following code

var entry = new entryModel();
entry.name = "new name";
entry.description= "new description";

compoModel.findOne(query, function (err, item) {
  if (item) {
    item.entries.push(entry);
    item.save(function (err) {
      if (!err) {
        log.debug('Entry added successfully.');
      } else {
        log.error("Mongoose couldn't save entry: " + err);
      }
    });
  }
});

It yields an error: TypeError: Object.keys called on non-object

What have I missed?

Problem courtesy of: Pekka

Solution

So I managed to get it working via the Model.update method by simply adding a new object to the compo.entries list and calling compoModel.update.

Solution courtesy of: Pekka

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Add document to an embedded document array

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×