gpt4 book ai didi

node.js - 如何在 Mongoose 中保存对象数组

转载 作者:IT老高 更新时间:2023-10-28 13:15:26 26 4
gpt4 key购买 nike

我有这个来自角度的数据

 {
"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]
});

以及如何将其保存到服务器 Controller 中的模型

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

当我使用此架构和此 Controller 时,我在集合中得到空记录,但名称和 ObjectId 除外。如何创建正确的 Schema 和 Controller ?

最佳答案

您需要在创建架构后创建一个 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 } );

关于node.js - 如何在 Mongoose 中保存对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35024285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com