1

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

My similar issue (same error) was solved by clearing the sub-document array. It was populated prior to the definition of the sub-document scheme. At least this is what i think happened.

E.g.:

var token = new Schema( { value: String, expires: Date } )
var user = new Schema( { username: String, tokens: [token] } )

.. and, prior to defining the 'token' scheme i had entries such as:

{ username: 'foo', tokens: ['123456'] }

.. so, clearing tokens did it for me.

user.tokens = []
user.save()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.