所以我有一段相当简单的代码如下
db.get().collection('bars').insert({
barID: req.body.button,
}, {
$push: {
usersfbID: req.body.profileUser[0].facebookID
}
}, function(err, doc) {
if (err) {
throw err;
}
if (doc) {
console.log('Had to create a new document for this bar');
console.log(doc);
//callback(null, doc);
}
});
因此,我只是检查一个条形文档是否存在,如果它不存在,那么我就创建该文档。我想为usersfbID字段插入一个数组,以便我可以存储前往该栏的所有用户。
但是,当我运行代码时,我没有收到错误,并且说文档已插入,但是当文档记录时,它没有userfbID字段。
那么我做错了什么? $ push运算符只能使用db的update方法吗?如果是这样,我如何为该字段插入数组?
答案 0 :(得分:2)
是的,它确实适用于更新方法
参考>运营商> Update Operators >阵列更新运算符> $ push
插入新条目意味着输入字段。在这种情况下,没有$ push操作,因为条目的数组是新创建的并且可以显式设置(usersfbID:[req.body.profileUser[0].facebookID]
,这意味着你期望该条的几个fbId)。更新集合元素中的数组不是插入,而是更新。
答案 1 :(得分:0)
所以,只是为了解答我面临的问题...... 是的,您只能在mongoDB文档上使用$ push或$ addToSet进行更新操作
这是我实现代码的方式。
db.get().collection('bars').update({
barID: req.body.button,
}, {
$addToSet: {
usersfbID: req.body.profileUser[0].facebookID,
usersDocID: req.body.profileUser[0]._id
}
}, {
upsert: true
}, function(err, doc) {
if (err) {
console.log('There is an error here');
throw err;
}
if (doc) {
console.log('Had to create a new document for this bar');
callback(null, doc);
}
});
upsert:true如果更新方法无法找到指定的文档,则确保插入新文档。