想要编写查询以检查mongodb中是否存在user_id=10
的内容。如果user_id=10
已存在,请编辑其他字段。如果它不存在,则插入user_id = 10以及其他字段。
我正在使用meteor js。
以下是代码:
Meteor.methods({
'dbs.update'(user_id,name,add)
{
if (Dbs.find){user_id:user_id}))
{
if(typeof name !=="undefined" && name)
{
Dbs.update({user_id:user_id},{$set: {name: name}});
}
if(typeof add !=="undefined" && add)
{
Dbs.update({user_id:user_id},{$set: {add:add}});
}
}
else
{
Dbs.insert({user_id:user_idname:name,add:add});
}
}
使用此代码,我可以更新现有记录。但如果不存在则无法插入新记录。
db.collection.find({ "user_id" : { $exists : true}})
:检查字段user_id
是否存在。那么是否有任何查询来检查字段user_id
中是否存在特定的ID /值?
答案 0 :(得分:1)
根据您的最新评论,以下内容应该有效。
Meteor.methods({
'dbs.update' (user_id, name, add) {
// find at least one doc which contains the user_id passed.
var getUserDocument = Dbs.findOne({
user_id: user_id
});
if (getUserDocument) { // if there exists a document with the given user_id
// do your update stuff here
} else { // if no doc has been found with user_id (which means that getUserDocument will be undefined)
//do your insert.
Dbs.insert({
user_id: user_id,
name: name,
add: add
});
}
}
});