-
尝试
$push
如果给定用户还没有评级,即否定
user_email
在更新查询的匹配部分。
-
在上再次执行第二次更新
"ratings.user_email": user_email
$set
在
"ratings.$": rating
.
结果应该是这样的:
collection.updateOne(
{ _id: o_id, ratings: { $not: { $elemMatch: { user_email: user_email } } } },
{ $push: { ratings: rating } }
);
collection.updateOne(
{ _id: o_id, "ratings.user_email": user_email },
{ $set: { "ratings.$": rating } }
);
// BEGIN new rating query/update variables
var query_new_rating = { _id: o_id, ratings: { $not: { $elemMatch: { user_email: user_email } } } };
var update_new_rating = { $push: { ratings: rating } };
// END new rating query/update variables
// part 01 - attempt to push a new rating
collection.updateOne(query_new_rating, update_new_rating, function(error, result) {
if (error) {
res.send(error);
} else {
// get the number of modified documents
// if 0 - the rating already exists
// if 1 - a new rating was added
var number_modified = result.result.nModified;
// BEGIN if updating an existing rating
if (number_modified === 0) {
console.log("updating existing rating");
// BEGIN existing rating query/update variables
var query_existing_rating = { _id: o_id, "ratings.user_email": user_email };
var update_existing_rating = { $set: { "ratings.$": rating } };
// END existing rating query/update variables
// part 02 - update an existing rating
collection.updateOne(query_existing_rating, update_existing_rating, function(error, result) {
if (error) {
res.send(error);
} else {
console.log("updated existing rating");
res.json({ result: result.result })
}
});
}
// END if updating an existing rating
// BEGIN if adding a new rating
else if (number_modified === 1) {
console.log("added new rating");
res.json({ result: result.result })
}
// END if adding a new rating
}
});