V
V
VegasChickiChicki2020-10-27 15:34:59
MongoDB
VegasChickiChicki, 2020-10-27 15:34:59

How to push an object into the model array only if it is not there?

There is such a scheme:

const chat = new schema({
  name: {
    type: String,
    required: true,
    unique: true,
  },
  users: [{
    name: {
      type: String,
      required: true,
      unique: true,
    }
  }],
  messages: [{
    user: {
      type: String,
      required: true,
    },
    message: {
      type: String,
      required: true,
    },
    date: {
      type: String,
      required: true,
    }
  }]
}, {
  versionKey: false,
  collation: 'chat'
});


There is a request, the user is looking for chats, if he finds them, then he can join them (to 1 at a time (per request)).

It looks something like this:
router.post('/join', async (request, response) => {
  models.chat.findOneAndUpdate({
    name: request.body.data.chat.name
  }, {
    $push: {
      users: {
        name: request.body.data.user.name,
      }
    }
  }, {
    new: true,
    upsert: true,
  }, (error, chat) => {
    if (!error){
      response.json({
        status: true,
        body: {
          chat
        },
      });

      //console.log('Chat update! chat: ', chat);
    } else {
      //console.log('error: ', error);
    }
  });
});


I can’t understand if I can somehow indicate that if the users array already has an object with the name that comes in the request, then nothing needs to be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2020-10-27
@VegasChickiChicki

Change $push to $addToSet and voila ))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question