1

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);
            });
        });
1
  • Instead of $push, use $addToSet i.e. {$addToSet:{usersIds:req.body.userId}} Commented Jan 23, 2017 at 10:43

1 Answer 1

8

just use $addToSet instead of $push

app.put('/roomChat', (req, res) => {
     GroupChat.findByIdAndUpdate(req.body.roomId, {$addToSet:{usersIds:req.body.userId}},{safe: true, new:true},(err,room) => {
          console.log(room);
      });
});
Sign up to request clarification or add additional context in comments.

2 Comments

do i still need unique true ?
no, no need unique: true in your schema

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.