简体   繁体   English

如何在猫鼬中保存对象数组

[英]How to save array of objects in mongoose

I have this data from 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"
        }
     ]
}

and I want to save this in ProductSchema in mongoDb but I don't know how to create schema for this我想将其保存在 mongoDb 的 ProductSchema 中,但我不知道如何为此创建架构

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

and how to save it to model in server controller以及如何将其保存到服务器控制器中的模型

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

when I use this Schema and this controller I get empty record in collection except name and ObjectId.当我使用这个架构和这个控制器时,我在集合中得到了空记录,除了名称和 ObjectId。 How to create right Schema and controller?如何创建正确的架构和控制器?

You need to create a mongoose model after you create your schema, and then you can save it.创建模式后,您需要创建一个 mongoose 模型,然后您可以保存它。 Try something like this:尝试这样的事情:

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 } );

Of course, the above answer works, consider this as an alternative .当然,上述答案有效,请将其视为替代方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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