Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 );
    }
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...