我想更新文档内部数组中对象的一个变量。我有事件文档和附加到该事件的Users数组。所以我有一个特定的UserId。因此,首先,是否有可能在Mongoose查询的用户数组中找到该用户?因为我有事件文档,内部有用户数组,找到该用户后,我想更新其一个变量。
exports.disableUsers = (req, res, next) => {
let User;
users: req.body.users; ///users Array
for (var i = users.length - 1; i >= 0; i--) {
if (users[i] == req.params.id1) {
User = users[i]; ////Particular User
break;
}
}
Event.updateOne(
{ _id: req.params.id },
{
///don't Know how to Update??
}
)
.then(result => {
console.log(result);
if (result.n > 0) {
res.status(200).json({ message: "Verification successful!" });
} else {
res.status(401).json({ message: "Not authorized!" });
}
})
.catch(error => {
res.status(500).json({
message: "Verifying events failed!"
});
});
};
上面是我的disableusers
函数。因此,谁能告诉我如何在事件文档中的对象数组中查找和更新特定用户。我的eventSchema
看起来像这样:
const eventSchema = mongoose.Schema({
title: { type: String, required: true },
content: { type: String, required: true },
imagePath: { type: String, required: true },
startDate: { type: Date, required: true },
endDate: { type: Date, required: true },
category: { type: String, required: true },
is_private : { type: Boolean},
max_users: {type: Number},
eventFee: {type: Number},
event_manager: [{ name: String, phone: String, email: String }],
address: [{ street: String, city: String, state: String, country: String, zipcode: String }],
creator: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
verify:{type:Boolean,required:true},
users:[{id:String,email:String,PhoneNum:String,firstName:String,lastName:String,city:String,disable:{type:Boolean,default:false}}]
});
答案 0 :(得分:0)
如果将用户分成自己的集合,这会容易得多,那么您可以使用该用户进行更新。_id
但是在您当前的情况下,如果使用mongo 3.6+,则可以做到这一点
这会将user.disable更新为true 还允许您在一个查询中更新多个用户
Event.update(
{ _id: req.params.id},
{ $set: { "users.$[user].disable" : true } },
{
multi: true,
arrayFilters: [ { "user.<Primary Key To Identify User>": { $in:<Array of values to match to the primary key on user> } } ]
}
)