I have a thread model in mongoose, which has an id field of course and an likes field which includes all the users who has liked this thread before so that people can't like the same thread twice.
const ThreadSchema = new mongoose.Schema({
author: {
id: { type: ObjectID, required: true, ref: 'User' },
screen_name: { type: String, required: true },
picture: { type: String, required: true },
},
theme: { type: String },
text: { type: String, required: true },
comments: {
count: { type: Number, default: 0 },
},
likes: {
count: { type: Number, default: 0 },
users: [{
_id: false,
id: { type: ObjectID, ref: 'User' },
screen_name: { type: String },
picture: { type: String },
}],
},
}, {
timestamps: true,
});
When I do an update, I will validate the threadID and likes.users.id, and only do the update when the 2 conditions match.
addLike(threadID, user) {
return new Promise((resolve, reject) => {
this.updateOne(
{
_id: threadID,
'likes.users.id': { $ne: user.id },
},
{
$push: { 'likes.users': user },
$inc: { 'likes.count': 1 },
},
{ safe: true }
).exec()
.then((result) => {
if (result.nModified) {
resolve(result);
} else {
reject(new Error('Already liked or no such thread.'));
}
})
.catch((err) => {
reject(err);
});
});
};
It works. And the result I get is something like this:
{ n: 0, nModified: 0, ok: 1 }
I can use nModified to know whether the update happens or not.
When nModified = 0 it means nothing changes. Which means either is no thread match threadID or the user.id has already in likes.users.id.
My problem is:
I want to generate a more clear error message rather than 'Already liked or no such thread.' I want to know the which case it is, is it already liked? or is it no such thread.
I know i can achieve this by findById first, check than update.
But is there a better solution? Thanks