简体   繁体   中英

Add array to subdocument Mongoose

I am trying to add an array to an existing subdocument in Mongoose using Express, but I can't seem to figure it out

This is my Mongoose model:

var subitems = new mongoose.Schema({
  _id: ObjectId,
  title: String,
  messages: Array
});

var menuItems = new mongoose.Schema({
  title : String,
  subitem: [subitems]
}, {collection: 'menu_items'});

module.exports = mongoose.model("menu_items", menuItems);

I am using the ID from the subdocument to update the specific item in "subitem" This is the Express Update:

postController.postArticles = function(req, res,item) {
  var id = req.body.id;
  var saveData = {
    title: req.body.title,
    text: req.body.text
  };
  item.update({_id: id}, {$push:{messages: saveData}},(err, result) => {
  });
};

It is not adding anything to the db, anyone have an idea?

With mongoose you have to update the whole object. So, first you get item with find or findOne, and the you have to add the element to the array with push, and finally you call .save() method of the mongoose object. Something like this:

postController.postArticles = function(req, res,item) {
  var id = req.body.id;
  item.findOne({_id: id}, function(error, myItem) {
    var saveData = {
      title: req.body.title,
      text: req.body.text
    };
    myItem.messages.push(saveData);
    myItem.save();
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM