如何在save()期间将对象数组包含到Mongoose中?

时间:2017-06-09 10:07:19

标签: node.js mongoose

我在执行Modal.save()时需要将一个对象数组插入到新文档中。实现这一目标的最佳做法是什么?

如何插入此内容:

pip3

进入这个:

var array = [
  { "id" : "001", "itemName" : "itemName001" },
  { "id" : "002", "itemName" : "itemName002" },
]

所以它会返回这样的东西:

var newItemCollection = new Collection ({
    collectionName: req.body.collectionName,
    items: [
         { id : array.id, itemName: array.itemName, itemDescription: "Foo was here..." }
    ]
});
newItemCollection.save();

1 个答案:

答案 0 :(得分:0)

您可以直接拨打mongoose的create功能,

 var array = [
  { "id" : "001", "itemName" : "itemName001" },
  { "id" : "002", "itemName" : "itemName002" },
]

var items = [] 

array.forEach(function(entry) {
    entry['itemDescription'] = "Foo was here..."
    items.push(entry)
});

var data = {
    collectionName: req.body.collectionName,
    items: items
}


 Collection.create(data, function (err, res) {
    if (err) return handleError(err);
    console.log('saved')
})