Welcome to OGeek Q&A 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...