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

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...