Bububu Malibu
Bububu Malibu

Reputation: 13

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

Upvotes: 1

Views: 5286

Answers (1)

Charlie Fish
Charlie Fish

Reputation: 20586

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.

Upvotes: 2

Related Questions