gpt4 book ai didi

node.js - Mongoose 默认带 findOneAndUpdate

转载 作者:太空宇宙 更新时间:2023-11-04 02:57:42 25 4
gpt4 key购买 nike

我有以下架构:

var UserSchema = new Schema({
username: { type: String, required: true, unique: true },
displayName: { type: String, required: true },
registered: { type: Boolean, required: true, default: false }
});

然后我尝试使用 findOneAndUpdate 插入和对象:

  var user = {
displayName: "Test User"
}

User.findOneAndUpdate({username: "test"}, user, {new: true, upsert: true}, function(err, newUser) {
callback(err, newUser);
});

用户被正确创建(第一次尝试,因为它不存在)。但是注册字段不会设置为 false。当我执行 findOneAndUpdate 时会发生这种情况吗?

mongo查询结果:

> db.users.find().pretty()
{
"_id" : ObjectId("56255f415641ace1204de658"),
"username" : "Test",
"displayName" : "Test User"
}

最佳答案

在 Mongoose 文档中找到了这个:

findAndModify helpers support limited defaults and validation. You can enable these by setting the setDefaultsOnInsert and runValidators options, respectively.

以防其他人遇到这种情况。

 var user = {
displayName: "Test User"
}

User.findOneAndUpdate({username: "test"}, user, {setDefaultsOnInsert: true, new: true, upsert: true}, function(err, newUser) {
callback(err, newUser);
});

关于node.js - Mongoose 默认带 findOneAndUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33224283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com