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

Sli*_*lip 8 mongoose mongodb node.js express

我从角度来看这个数据

 {
     "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"
        }
        ]
}
Run Code Online (Sandbox Code Playgroud)

我想在mongoDb中的ProductSchema中保存它,但我不知道如何为此创建模式

var ProductSchema = new Schema({
name: String,
conditions:  [Array],
colors: [Array]
          });
Run Code Online (Sandbox Code Playgroud)

以及它如何保存到服务器控制器中的模型

 var product = new Products({
    name: req.body.name,
    conditions: req.body.conditions,
    colors: req.body.colors
});
Run Code Online (Sandbox Code Playgroud)

当我使用这个Schema和这个控制器时,我得到除了name和ObjectId之外的集合中的空记录.如何创建正确的架构和控制器?

Bri*_*laz 8

您需要在创建架构后创建一个猫鼬模型,然后您可以保存它.尝试这样的事情:

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 } );
Run Code Online (Sandbox Code Playgroud)