【问题标题】:How to check whether particular user_id is present in user_id field in mongodb如何检查mongodb的user_id字段中是否存在特定的user_id
【发布时间】:2017-12-04 18:29:43
【问题描述】:

想写一个查询来检查 user_id=10 是否存在于 mongodb 中。如果user_id=10 已存在,则编辑其其他字段。如果不存在,则插入 user_id=10 以及其他字段。 我正在使用流星 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/值?

【问题讨论】:

  • 您可以添加您现有 mongo 文档的示例吗?
  • {"_id" : "***", "user_id" : "", "name" : "", "add" : "" }
  • 我应该用这个替换什么:" if (Dbs.find){user_id:user_id}))" 如果检查我传递的 user_id 的条件是否存在。如果不存在则它应该转到其他部分:“Dbs.insert({user_id:user_idname:name,add:add});”其他代码运行良好。

标签: mongodb meteor


【解决方案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
            });
        }
    }
});

【讨论】:

  • 好吧,到底是什么不工作?它总是跳到else部分吗?
  • 当我传递新 id 时,它并没有将其插入数据库中。我只是使用“alert”来检查 getUserDocument 存储的内容。它显示未定义。
  • 这是服务器端代码。所以你必须console.log 来检查它是否被插入。或者直接查看mongo。确保您有正确的发布/订阅,以便客户端上可以使用相同的文档。如果没有,您将始终在客户端获得undefined。我希望这一切都得到了照顾。
  • 它的工作@blueren。我猜我输入错误所以它没有插入。非常感谢。终于它工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-27
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 2018-08-07
  • 2011-10-24
相关资源
最近更新 更多