Desired Behaviour
Add object to array of objects if it doesn't exist, otherwise update object.
Each user can only add one rating.
Schema
"ratings" : [
{
"user_email" : "[email protected]",
"criteria_a" : 0,
"criteria_b" : 3,
"criteria_c" : 1,
"criteria_d" : 5,
"criteria_e" : 2
},
{
"user_email" : "[email protected]",
"criteria_a" : 1,
"criteria_b" : 3,
"criteria_c" : 5,
"criteria_d" : 2,
"criteria_e" : 1
},
{
"user_email" : "[email protected]",
"criteria_a" : 5,
"criteria_b" : 3,
"criteria_c" : 1,
"criteria_d" : 0,
"criteria_e" : 1
}
]
What I've Tried
I've read this:
The
$addToSetoperator adds a value to an array unless the value is already present, in which case$addToSetdoes nothing to that array.
Source: https://docs.mongodb.com/manual/reference/operator/update/addToSet/
But I'm a bit confused because I think I am trying to:
$addToSetif object doesn't exist$set(ie update the existing object) if it does exist
The following keeps adding rating objects to the array, even if a user has already added a rating.
var collection = mongo_client.db("houses").collection("houses");
var o_id = new ObjectID(id);
var query = { _id: o_id, "ratings.user_email": user_email };
var update = { $addToSet: { ratings: rating } };
var options = { upsert: true };
collection.updateOne(query, update, options, function(err, doc) {
if (err) {
res.send(err);
} else {
res.json({ doc: doc })
}
});
Edit:
The following works if a user has already submitted a rating, but otherwise it throws the error The positional operator did not find the match needed from the query.:
var update = { $set: { "ratings.$": rating } };