跳你很好,我想我可以在这里找到一个合适的解决方案。我有简单的mongoDB和Node Js API。所以我的问题是在我的数据库集合中有多个产品,每个产品都有一个评论数组。当我尝试更新或删除任何数据到reviews数组元素时,它会将消息显示到控制台"记录添加为{ok:0,n:0,nModified:0}&#34 ; 即可。但我想成功插入和删除数据到评论数组。请参阅下面的功能和方法:
路线:
app.put('/notes/insertarray', notes.insertToArray);
对于控制器:
exports.insertToArray = function(req, err, res) {
var title = req.body.title;
var name = req.body.name;
var comment = req.body.comment;
var stars = req.body.stars;
var date = req.body.date;
Note.update(
{title:title},
{$push:{
reviews:{
$each:[
{
"name":name,
"comment":comment,
"stars":stars,
"date":date
}
]
}
}
},function(err, results){
console.log("Record added as ", results);
res(results);
});
};
我的数据模型如下:
{
"title": "Coffee Mug",
"slogan": "Keep your coffee hot!",
"description": "A mug is a type of cup used for drinking hot beverages, such as coffee, tea, hot chocolate or soup. Mugs usually have handles, and hold a larger amount of fluid than other types of cup. Usually a mug holds approximately 12 US fluid ounces (350 ml) of liquid; double a tea cup. A mug is a less formal style of drink container and is not usually used in formal place settings, where a teacup or coffee cup is preferred.",
"stars": 0,
"category": "Kitchen",
"img_url": "/img/products/mug.jpg",
"price": 12.5,
"reviews": [
{
"name": "",
"comment": "",
"stars": 5,
"date": 1456067725049
},{
"name": "",
"comment": "",
"stars": 5,
"date": 1456067725059
}
]
}
并发布文章请求
{
"title": "Coffee Mug",
"name": "this is slogan2",
"comment": "This is description",
"stars": 3.4,
"date": 220
}
答案 0 :(得分:0)
$ 因为这是json,所以不需要$ each
{$push:{
reviews:{
"name":name,
"comment":comment,
"stars":stars,
"date":date
}
}