【问题标题】:How to find one object in mongodb [duplicate]如何在mongodb中找到一个对象[重复]
【发布时间】:2019-07-27 07:19:46
【问题描述】:

我是 mongodb 的新手,我正在尝试将从输入中键入的名称与保存在我的集合中的名称进行比较,如果存在相同的名称,我想在该对象名称的数据库中增加“numberOfSearches”,如果没有让它在集合中创建那个。毕竟我不知道如何比较“if”中的那些名字,我应该使用 Find 方法还是有其他方法呢?

    app.post('/stronka', function(req,res){
    var obj = {name: req.body.chosenCity, numberOfSearches: 1};

    if(db.collection('miasta').find({name: obj.name})){
        db.collection('miasta').updateOne(
            {"name": obj.name},
            {$inc: {"numberOfSearches": 1}}
            )
        res.redirect('/stronka');
        console.log("first option");
    }
    else{
        db.collection('miasta').insertOne(obj, function(err, result){
            if(err) return console.log(err);

            console.log('saved to database')
            res.redirect('/stronka');
        })
        console.log("sec option");
    }


})

【问题讨论】:

    标签: node.js mongodb collections


    【解决方案1】:

    您可能会遇到的一个问题是db.collection('...').find() 将返回异步Promise 而不是同步值。为了使用find() 的结果,你需要await 它这样:

        app.post('/stronka', async function(req,res){ <-- note the addition of the async keyword
        var obj = {name: req.body.chosenCity, numberOfSearches: 1};
        const result = await db.collection('miasta').find({ name: obj.name });
        if (result) {
           ....
        } else {
           ...
        }
    });
    

    您需要对 updateOne 和其他对 MongoDb 的调用应用类似的原则,但我将把它作为练习留给您(:

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2014-09-17
      • 2019-04-25
      • 2021-02-20
      • 1970-01-01
      • 2021-11-15
      • 2018-11-22
      • 2013-03-31
      • 1970-01-01
      相关资源
      最近更新 更多