gpt4 book ai didi

node.js - Mongoose 更新单个属性失败

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:01 24 4
gpt4 key购买 nike

首先我已阅读并尝试了mongoose-and-partial-select-update帖子中的解决方案。但是,当我尝试使用传统样式时,查询会起作用。

我的架构:

var userSchema = mongoose.Schema({
local: {
email: {
type: String,
index: {
unique: true,
dropDups: true
}
},
password: String,
displayName: String,
avatar: {
type: String,
default: "./img/user.png"
},
role: {
type: String,
default: "student"
},
ask_history: [
{
question_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'questionAnswer'
},
favorite: Boolean,
ask_time: Date
}
],
interest: [String]
}
})

工作更新功能:

User.findById(id, function(err, User) {
if (err) {
throw done(err);
}
if (!User) {
return;
}
User.local.role = "admin";
User.save(function(err, updatedUser) {
if (err) {
throw err
} else {
//good
}
})
});

但是如果我这样做:

User.update({_id : id},
{$set{
local:{role:"admin"}
}
},function(...){...}
});

上面的代码会将用户覆盖为:

{
_id : "...",
local: {
role : "admin"
}
}

我读到 $ 将使更新仅更改属性,我哪里做错了?

最佳答案

位置运算符 $ 适用于子文档数组。

在您的情况下,您有一个子文档,因此以下内容应该有效:

User.update({_id : id},
{ $set
{
"local.role": "admin"
}
}, function(...){...}
});

关于node.js - Mongoose 更新单个属性失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41643984/

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