I am having a problem where an object in my document would not get updated. In my Class
Model, there's a field called sentiment of type Object
as the following:
sentiment: {
terrible: 0,
bad: 0,
okay: 0,
good: 0,
fantastic: 0
}
The way I implemented sentiment
in my model is as following:
sentiment: Object
To update the property, I am passing an object with the field sentiment
that contains the actual sentiment:
{ sentiment: 'good' } // this is what req.body contains
I am doing this:
const classFound = await Class.findById(req.params.classId);
if (classFound) {
classFound.sentiment[req.body.sentiment] += 1;
await classFound.save();
}
But when I retrieve the class, the sentiment
object remains unchanged. I am not sure where the bug is because when I log out classFound
after save()
, I get the updated sentiment object.
EDIT
Class.js // class Schema
const classSchema = new Schema({
name: {
type: String,
required: true
},
abbr: {
type: String,
required: true
},
sentiment: {
terrible: { type: Number, default: 0 },
bad: { type: Number, default: 0 },
okay: { type: Number, default: 0 },
good: { type: Number, default: 0 },
fantastic: { type: Number, default: 0 }
}
});
try this
const update = (query, body) => {
return new Promise((resove, reject) => {
Class.update(query, body, (err, data) => {
if (err)
return reject(err);
return resove(data);
});
});
}
const classFound = await Class.findOne({
_id: req.params.classId
}).exec(); // exec returns promise
if (classFound) {
const sentiment = req.body.sentiment;
classFound.sentiment[sentiment] = classFound.sentiment[sentiment] ? classFound.sentiment[sentiment] + 1 : 1;
const query = {
_id: req.params.classId
};
const body = {
$set: {
sentiment: classFound.sentiment
}
};
await update(query, body);
}
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.