I'm trying to create group chat application. But when i put same id(string) to the array, the unique true does not work and the same id is added to the array and i end up with this for example. I want the userIds array of IDs to contain only unique ID's
{ _id: 5885dc260a6bd22768bef387,
roomName: 'Room1',
author: '587cd401a279b834b0a4cb8d',
__v: 0,
messages: [],
usersIds:
[ 587cd401a279b834b0a4cb8d,
587cd3ed7bd35b37d4c75a36,
587cd3ed7bd35b37d4c75a36 ] }
This is my room schema
const roomChat = new Schema({
roomName: String,
author: String,
usersIds:[
{
type: Schema.ObjectId,
unique: true
}
],
messages: [
{
author: String,
text: String,
date: Number
}
]
});
This is how i add users into userIds in particular room
app.put('/roomChat', (req, res) => {
GroupChat.findByIdAndUpdate(req.body.roomId, {$push:{usersIds:req.body.userId}},{safe: true},(err,room) => {
console.log(room);
});
});
$push, use$addToSeti.e.{$addToSet:{usersIds:req.body.userId}}