O
O
Orc2020-02-12 05:26:46
MongoDB
Orc, 2020-02-12 05:26:46

How to limit adding a document to MongoDB based on the result of a check?

Now the existing construction for some reason adds the document to the database based on the result of the check, in any case, the entry to the database is triggered even if false.

>> Handler

chatCreate = (req, res) => {

    const chat = new Chat({
        nickname: req.body.nickname,
        message: req.body.message
    });

    chat.save()
        .then(chat => {

            Room.find({
                'room_name': {$in: req.body.room}
            }, (err, rooms) => {

                if (err) {
                    return res.send(err);
                }

                 // тут проверяем наличие записи в БД и по результату выполняем действие
                if (rooms.length !== 0) {

                  chat.room = rooms;
                  chat.save(function (err) {

                      if (err) {
                          return res.send(err);
                      }

                      let answer   = {};
                      answer.state = 'success';
                      answer.text  = 'Message post successfully!';
                      let newarray = answer.concat(chat);
                      res.send(newarray);
                  });
                } else {
                   return res.send(err);
                }
            });
        })
        .catch(err => {
            res.status(500).send(err);
        });
};


>> Room storage base model
const mongoose = require('mongoose');
const RoomSchema = mongoose.Schema({

    room_name: String,
    created_date: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Room', RoomSchema);


>> Message storage database model
const mongoose = require('mongoose'), Schema = mongoose.Schema;
const ChatSchema = mongoose.Schema({

    room: [{ type: Schema.Types.ObjectId, ref: 'Room' }],
    nickname: String,
    message: String,
    created_date: { type: Date, default: Date.now }
});

module.exports = mongoose.model('Chat', ChatSchema);


>> Even if the condition if (rooms.length !== 0) > false , the document is still added to the database
5e4371aea43ef136846405.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question