Mongoose unique true not working in array of strings [duplicate]

518
January 23, 2017, at 6:48 PM

This question already has an answer here:

  • Unique array values in Mongoose 3 answers

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);
            });
        });
Answer 1

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);
      });
});
Rent Charter Buses Company
READ ALSO
Deploy a NodeJS app to Heroku

Deploy a NodeJS app to Heroku

I've followed the getting started guide to deploy a nodejs application to heroku:

447
Rename file using custom npm script

Rename file using custom npm script

I want to make a script for my angular2 project that renames READMEmd to README_2

585
TLS error sending out mail with nodemailer

TLS error sending out mail with nodemailer

I am using nodejs nodemailer v2

659
bootstrap datetime picker off by one day in some timezones

bootstrap datetime picker off by one day in some timezones

I have a list of posts where among other data I display date and allow users to edit posts including the actual expiry datethat said, date on the post looks normal but clicking on edit button which shows fields and datetimepicker widget if off by one day in some timezones...

388