简体   繁体   中英

Mongoose push - find or update to array of objects

My situation is as following:

I have a session collection, each session is a chatroom.

When a user sends a new message, other users should be notified, but to prevent spam, I need to build a check if a user got a notification mail in the last 10 minutes.

So my session collection has a notification array of objects with: sessionId , userId and date

Everytime someone sends a new message, I have to send the mails and push to the notifications column, but it should overwrite the userId to prevent the notifications column from growing.

This is what I've tried:

sessionSchema .findByIdAndUpdate(sessionId, { $push: { notifications: { userId: userId, date: moment().utc().toDate() } } }, callback)

However with push, the column keeps growing. How can I use push to overwrite the already created notifications by a certain userId?

Maybe, try to add options in query to DB.

sessionSchema
          .findByIdAndUpdate(sessionId, {
            $push: {
              notifications: {
                userId: userId,
                date: moment().utc().toDate()
              }
            }
          }, { new: true }, callback)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM