Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

node.js - Mongoose: return a boolean variable if entry not present in array

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'
            ]
        }
    }}
]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...