Reputation: 348
Can I return a boolean variable as per the conditions in a mongoose query? Example, while getting all notification of a user, I want to show if a notification is seen by the user or not.
I have this schema:
const notificationSchema = mongoose.Schema({
userid: { type: mongoose.Schema.Types.ObjectId, ref:'User', require: true, unique: false },
time: Number,
type: Number,
seenBy: {type: [String], default: []} // can have very large number of values (user IDs)
}, {__v: false});
Now while getting the notifications array I want to get an extra field which seen
which is true if a specific user exists in respective seenBy[] array of the field.
such that I get the response object like
1 new notification
[{userid: <someid>, time: ... <other fields> ..., seen: false}]
Thank you
Upvotes: 0
Views: 1554
Reputation: 103365
You would have to run an aggregation operation in which you use the $setIsSubset
operator on two arrays i.e. the [userId]
and seenBy arrays which
returns true when the first array is a subset of the second, including when the first array equals the second array, and false otherwise.
The first userid array should be a string array since you will be comparing the array with another of string type so you need to convert the ObjectId to string using $toString
.
As an example, the following shows the query:
const userId = '5ffafefe288e7a58ff08226e'; // the user id input variable as a string, could be from req.params.id or req.query.userId etc
const notifications = await Notification.aggregate([
{ '$match': { userid: mongoose.Types.ObjectId(userId) } },
{ '$addFields': {
'seen': {
'$setIsSubset': [
[{ '$toString': '$userid' }],
'$seenBy'
]
}
}}
]);
Upvotes: 3
Reputation: 8172
You should try
async func () {
const doesUserExit = await User.exists({ _id: userid });
}
Read more model.exists, will return true or false.
Upvotes: 1