[英]How to insert data of a single form into two collections using nodejs and mongodb
[英]How to insert or delete data into mongodb collections in existing array for nodejs API?
跳你很好,我想我可以在这里找到一个合适的解决方案。 我有简单的 mongoDB 和 Node Js API。 所以我的问题是在我的数据库集合中有多个产品,每个产品都有一个评论数组。 当我尝试更新或删除评论数组元素中的任何数据时,它会在控制台中显示消息“记录添加为 { ok: 0, n: 0, nModified: 0 }” 。 但我想成功地将数据插入和删除到评论数组中。 请看下面我的功能和方法:
对于路线:
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
}
如果传递数组,则使用 $each 因为这是 json ,所以不需要 $each
{$push:{
reviews:{
"name":name,
"comment":comment,
"stars":stars,
"date":date
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.