1

I'm new to mongodb and am trying to compare a name typed from a input with a names saved in my collection and if there is this same name i want to increment "numberOfSearches" in database of this object name and if not let it create that one in collection. After all i don't know how to compare those names in "if", should i use Find method otherwise or there is other method for that?

    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");
    }


})
Yoshua
  • 11
  • 1

1 Answers1

0

One problem that you will likely run into here is that db.collection('...').find() will return an asynchronous Promise not a synchronous value. In order to use the result of the find(), you need to await it as such:

    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 {
       ...
    }
});

You will need to apply a similar principle to the updateOne and other calls to MongoDb, but I'll leave that as an exercise for you (:

jakemingolla
  • 1,613
  • 1
  • 10
  • 13