我有这个架构:
var UserSchema = new Schema({
name: String,
username: {
type: String,
required: [true, "Please enter a username"],
minlength: [6, "Username must be at least 6 characters"],
maxlength: [15, "Username cannot exceed 15 characters"],
unique: true
},
password: {
type: String,
required: [true, "Please enter a password"],
minlength: [6, "Password must be at least 6 characters"],
maxlength: [17, "Password cannot exceed 17 characters"],
},
roommates: [{roomate: {type: Schema.Types.ObjectId, ref: "User"}, status: {type: String, default: "pending"}}]
})
这是我的控制器(id只是我在我的数据库中的两个随机用户ID,所以忽略它:
update: function(req, res) {
User.findOne({
_id: "57f1645c05ec06099ead3db6", 'roommates._id': "57f16436190a09099a1ddbde"
}, {'roommates.$': 1}, function(err, user1) {
user1.update()
})
}
}
我的控制器现在完全无用。目标是到达室友阵列内部,找到一个特定对象,然后更新那个,以便它的状态从“待定”(这是默认值)变为我可以在控制器中设置的新字符串值。
我在查询中迷路了。你会怎么用猫鼬做到这一点?
由于
答案 0 :(得分:0)
以下是答案:
update: function(req, res) {
User.findOneAndUpdate({
_id: "57f16436190a09099a1ddbde", "roommates._id": "57f1645c05ec06099ead3db6"
}, {$set: {"roommates.$.status": "active"}}, function(err, res) {
if (err) {
console.log(err);
} else {
console.log("status updated");
}
})
}