Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose findByIdAndUpdate upsert returns null document on initial insert

This basic Mongoose model code returns a null result (gameMgr) on the initial call, but works on subsequent calls. Shouldn't it return a populated result object on the initial upsert? The mongo record exists, and running the code a second time in the identical situation, everything works fine as there is no insert.

If a null result object is expected, what is the appropriate pattern to create a new object? (or do I reload with another db call and descend further into callback madness?)

GameManagerModel.findByIdAndUpdate(
    game._id,
    {$setOnInsert: {user_requests:[]}}, 
    {upsert: true},
    function(err, gameMgr) {
        console.log( gameMgr ); // NULL on first pass, crashes node
        gameMgr.addUserRequest( newRequest );
    }
);
like image 426
Stickley Avatar asked Oct 16 '25 17:10

Stickley


1 Answers

In Mongoose 4.0, the default value for the new option of findByIdAndUpdate (and findOneAndUpdate) has changed to false (see release notes). This means that you need to explicitly set the option to true to get the doc that was created by the upsert:

GameManagerModel.findByIdAndUpdate(
    game._id,
    {$setOnInsert: {user_requests:[]}}, 
    {upsert: true, new: true},
    function(err, gameMgr) {
        console.log( gameMgr );
        gameMgr.addUserRequest( newRequest );
    }
);
like image 163
JohnnyHK Avatar answered Oct 18 '25 07:10

JohnnyHK