D
D
Demigodd2019-09-21 10:49:21
MongoDB
Demigodd, 2019-09-21 10:49:21

How to check if the id is in the array during the request?

For example, there is a Room, Message and User model.

Schema Message = {
  title: { type: Schema.Types.String, require: true },
  room: { type: Schema.Types.ObjectId, ref: "User" },
  user: { type: Schema.Types.ObjectId, ref: "User" },
  hideForUsers: [{ type: Schema.Types.ObjectId, ref: "User" }],
}

MessageModel.find({ room: roomId});
Here I find all messages by room ID.
During the request, I have a UserId, how to check if this UserId is in the hideForUsers array of the Message and if it exists then exclude this document for the final result.
I don't know if I'm doing it right. We need the functionality to delete messages from the room with the ability to delete your message for yourself or for all users in the room.
If I chose for myself, then I want to add my UserId to the hideForUsers array, and when requested, determine whether to show this message for me or not.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-09-21
@Demigodd

Not this?

MessageModel.find({ 
  room: roomId, 
  hideForUsers: { $nin: [ UserId ] }
})

to ensure uniqueness in the array there is $addToSet
https://docs.mongodb.com/manual/reference/operator...
$pull with conditions
https://docs.mongodb.com/manual/reference/operator...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question