首页 > 解决方案 > 使用 Mongoose 将嵌套对象添加到对象

问题描述

我正在尝试在 Mongoose 中添加一个嵌套项目,但我似乎无法让它工作。我正在尝试将“消息”对象添加到现有的“子项”对象

我在 MongoDB 中的 JSON

{
    "_id" : ObjectId("5c33438d3d1e1323111fce6e"),
    "title" : "Nieuws",
    "__v" : 0,
    "subitem" : [ 
        {
            "title" : "Nieuwsberichten",
            "messages" : [ 
                {
                    "title" : "bericht1"
                }, 
                {
                    "title" : "bericht2"
                }
            ]
        }, 
        {
            "title" : "Nieuwsarchief"
        }, 
        {
            "title" : "Nieuwsbrief"
        }
    ]
}

在快递:

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:{'subitem.messages': saveData}},(err, result) => {
  });
};

和猫鼬模型:

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

标签: mongodbexpressmongoose

解决方案


您的架构与您的 JSON 对象不匹配。在您的 Schema 消息中是一个对象,而在 JSON 中它是一个对象数组。

尝试以下架构:

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

推荐阅读