猫鼬findByIdAndUpdate upsert在初始插入时返回空文档 [英] Mongoose findByIdAndUpdate upsert returns null document on initial insert
问题描述
此基本的Mongoose模型代码在初始调用时返回空结果(gameMgr),但在后续调用中起作用.它不应该在初始upsert中返回填充的结果对象吗? mongo记录存在,并且在相同情况下第二次运行代码,因为没有插入,所以一切正常.
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 );
}
);
推荐答案
在Mongoose 4.0中,findByIdAndUpdate
(和findOneAndUpdate
)的new
选项的默认值已更改为false
(请参见发行说明).这意味着您需要将选项显式设置为true
以获得由upsert创建的文档:
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 );
}
);
这篇关于猫鼬findByIdAndUpdate upsert在初始插入时返回空文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!