chenchen liu chenchen liu - 2 months ago 53
Node.js Question

When I try to insert subdoc into mongodb with the help of mongoose,It returns “cannot use the part (...”

I have this really annoying issue where i can't update anything using Mongoose. It's really frustrating to use, and the documentation is not helping at all.

Here is my schema:

var CRMModel = mongoose.model('CRM', new Schema({
title: { type: String, index: true }
, author: String
, remarks: String
, date: { type: Date, default: Date.now() },
comments:[{
title:String,
seq:Number,
date:{ type: Date, default: Date.now() }
}]
})
);


And this is the code where I want to add a comment to the array
comments
:

CRMModel.update({_id:crmId.trim()},{ $push: { 'comments.title': req.body.title, 'comments.seq': req.body.seq} },
{upsert:true},
function(err, customer){
if(err){
console.log(err);
}
}
);


At this point I get the error:

{ [MongoError: cannot use the part (comments of comments.title) to traverse the element ({comments: []})]
name: 'MongoError',
message: 'cannot use the part (comments of comments.title) to traverse the element ({comments: []})',
driver: true,
index: 0,
code: 16837,
errmsg: 'cannot use the part (comments of comments.title) to traverse the element ({comments: []})' }


I have looked for the similar problems on Stack Overflow but I did't solve this. I will be grateful if anyone can help me.

Answer

The "argument" to $push should be an array field, which in your case is comments:

{
  $push : {
    comments : {
      title : req.body.title,
      seq   : req.body.seq
    }
  }
}
Comments