如何在Mongoose中保存对象数组

15

我从angular获取了这些数据

 {
     "name": "Test name",
     "conditions": [
        {
         "id": "56a53ba04ce46bf01ae2bda7",
         "name": "First condition"             
        },
        {
         "id": "56a53bae4ce46bf01ae2bda8",
         "name": "Second condition"
        }
     ],
     "colors": [
        {
         "id": "56a545694f2e7a20064f228e",
         "name": "First color"
        },
        {
         "id": "56a5456f4f2e7a20064f228f",
         "name": "Second color"
        }
     ]
}

我想将这个存储在mongoDb的ProductSchema中,但我不知道如何为此创建模式。

var ProductSchema = new Schema({
    name: String,
    conditions:  [Array],
    colors: [Array]
});

如何将其保存到服务器控制器中的模型

 var product = new Products({
    name: req.body.name,
    conditions: req.body.conditions,
    colors: req.body.colors
});
当我使用这个Schema和这个controller时,除了名字和ObjectId之外,在集合中得到的记录为空。如何创建正确的Schema和controller?

它不是对象数组,只是一个对象。 - Стас Рябцев
2个回答

12

在创建模式之后,您需要创建一个mongoose模型,然后才能保存它。尝试像这样:

var ProductSchema = new Schema({
name: String,
conditions:  [{}],
colors: [{}]
          });

var Product = mongoose.model('Product', productSchema);

var product = new Product({
    name: req.body.name,
    conditions: req.body.conditions,
    colors: req.body.colors
});

product.save( function(error, document){ //callback stuff here } );

是的,我尝试过了,但我觉得这个模式可能有误或者在 conditions: req.body.conditions, colors: req.body.colors 中存在错误。我只能在我的集合中获取已保存的名称和对象ID,没有条件或颜色。 - Slip
修改了我的回答...我认为你需要更改条件和颜色的模式类型。 - Brian Glaz
对我有用,谢谢! - Rajan Patil
当我尝试保存时,它保存在第0个索引处,但是这里有2个元素: 服务:"[{"service": "A1", "price": "1000"}, {"service": "A2", "price": "100..." - Mohit Saxena
我有一个问题,当我向条件数组中添加一个新对象时,之前的值会被覆盖还是只会添加到数组的最后? - OT AMD

1

当然,上面的答案是可行的,但考虑这个替代方案

var defaultArray = ["A","B","C"];
var schemaDef = mongoose.Schema(       
  permission: { type: Array, default: defaultArray },
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接