node.js 如何在猫鼬中保存对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35024285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to save array of objects in mongoose
提问by Slip
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 it save 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. How to create right Schema and controller?
当我使用这个架构和这个控制器时,我在集合中得到了空记录,除了名称和 ObjectId。如何创建正确的架构和控制器?
采纳答案by Brian Glaz
You need to create a mongoose model after you create your schema, and then you can save it. Try something like this:
创建模式后,您需要创建一个 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 } );

