I want to Update one variable of an object in array Inside my document. I have the events document and Users array attached to that event. So I have a particular UserId. So firstly, Is it Possible to find that user inside the array of Users with Mongoose query? Because I have events document and inside I have User's array.After finding that User, I want to update its one variable.
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!"
});
});
};
Above is my disableusers
Function. So can anyone please tell how to find and Update a particular user in Array of Objects Inside the event Document. And My eventSchema
looks like this:
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}}]
});
This would be much easier if you separated users in to its own collection, then you could just update using the user._id
However in your current case, it can be done like this if using mongo 3.6+
this will update user.disable to true also allows you to update multiple users in one query
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> } } ]
}
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.