I want to only update two values inside todo in the Mongoose model below
const userSchema = new mongoose.Schema({
name: String,
email: String,
phone: Number,
points: Number,
todo: {
}
})
The todo actually contains 11 values and I only want to update 2 values at a time which I am getting from the frontend
let {
t,
i
} = req.body.delitem;
await User.updateOne({
username: req.body.user
}, {
$set: {
todo: {
[t]: "",
[i]: ""
}
}
})
but what is happening is these two fields are getting set to blank strings but the remaining fields are also changing to NULL
whereas I want the other fields to stay the same.
CodePudding user response:
Use dot notation like this:
await User.updateOne({username:req.body.user},
{
"$set": {
"todo.t": "",
"todo.i": ""
}
})
Example here
If you use an object into $set
you are telling mongo to replace the object by the new one.
CodePudding user response:
I believe your issue is that you're using $set and passing a whole object which overwrites the whole todo with your t
and i
fields and you've enforced required on those other fields.
If you see the docs in mongo for $set you can instead update specific fields in subobjects. The following snippet should be more appropriate.
let {t,i} = req.body.delitem;
await User.updateOne({username:req.body.user}, {
$set: {
"todo.t": "",
"todo.i": ""
}
})