Bububu Malibu Bububu Malibu - 7 months ago 123
Node.js Question

FindOne mongo return null

I try to find film and if it doesn't exist yet, add it in database.

let film = Films.findOne({ "id" :id }, function(err, doc) {
if (err) throw err;
else console.log("Film is "+doc);
});

if (!film){
film = {"id" : id};
Films.insertOne(film);
}


console.log
gives
null
, so there are no errors but it can't create new film in database. Could you please say what I'm doing wrong

Answer Source

Try the following code. The problem has to do with async. You need the findOne to return before you call the if statement.

Films.findOne({ "id" :id }, function(err, doc) {
    if (err){
        // error
        throw err;
    } else if (doc) {
        // film exists
        console.log("Film is "+doc);
    } else {
        // film doesn't exist
        var film = new Films({"id" : id});
        film.save();
    }
});

That code will find one item with id = to your id variable and call the function provided when complete, passing in any errors and the document it found (or null if no document was found).

Then will print the document if it exists, otherwise it will create a new film object and save it to the database.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download