我的架构如下
var DeptSchema = new Schema({
name : {type : String, default: ''},
sku : {type : String, default: ''}, // (SKU = stock keeping unit)
Product : {
name : {type : String, default: '', unique:true},
sku : {type : String, default: '', unique:true}, // (SKU = stock keeping unit)
description : {type : String, default: '100gm'},
price : {type : String, default: ''},
quantity : {type : Number, default: '0'},
isFav : {type : Boolean, default: 'false'}
}
});
通过Mongoose我创建了一个API,但是当我想将产品添加到特定的部门(部门)时,问题开始了,创建了一个全新的部门实例,而不是将新产品附加到现有的部门。<登记/> 我的POST / PUT如下所述
.put(function(req, res) {
// use our Dept model to find the Dept we want
Dept.findById(req.params.Dept_id, function(err, Dept) {
if (err)
res.send(err);
Dept.name = req.body.name; // update the Dept info
Dept.sku = req.body.sku;
Dept.Product.name = req.body.ProductName;
Dept.Product.sku = req.body.ProductSKU;
Dept.Product.description = req.body.ProductDescription;
Dept.Product.price = req.body.ProductPrice;
Dept.Product.quantity = req.body.ProductQuantity;
Dept.Product.isFav = req.body.ProductisFav;
// save the Dept
Dept.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Department updated!' });
});
});
})
.post(function(req, res) {
var dept = new Dept(); // create a new instance of the Dept model
dept.name = req.body.name; // set the Dept name (comes from the request)
dept.sku = req.body.sku;
dept.Product.name = req.body.ProductName;
dept.Product.sku = req.body.ProductSKU;
dept.Product.description = req.body.ProductDescription;
dept.Product.price = req.body.ProductPrice;
dept.Product.quality = req.body.ProductQuality;
dept.Product.isFav = req.body.ProductisFav;
// save the Dept and check for errors
dept.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Department created!' });
});
})
e.g。我们可以很容易地从输出中看到,不同水果而不是追加到同一个水果部门正在创建另一个实例。另外,为什么ProductSchema没有自动生成的Object Id?
[
{
"__v": 0,
"_id": "5528027cd4eb13d80cf81f87",
"Product":
{
"isFav": true,
"quantity": 34,
"price": "128",
"description": "1kg",
"sku": "APL",
"name": "Apple"
},
"sku": "FRT",
"name": "Fruits"
},
{
"_id": "552824abd67bf9d81391ad92",
"__v": 0,
"Product":
{
"isFav": true,
"quantity": 0,
"price": "40",
"description": "1kg",
"sku": "ORG",
"name": "Orange"
},
"sku": "FRT",
"name": "Fruits"
}
]
感谢您的耐心等待。
答案 0 :(得分:1)
您已声明Product为对象而非数组。
Product: {...}
- &gt; Product: [{...}]
此外,您需要更新put方法以将新项目推送到Dept.Product数组而不是更新Dept的属性。您可以阅读如何在documentation中正确使用subdoc。