Answer the question
In order to leave comments, you need to log in
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);
});
};
const mongoose = require('mongoose');
const RoomSchema = mongoose.Schema({
room_name: String,
created_date: { type: Date, default: Date.now }
});
module.exports = mongoose.model('Room', RoomSchema);
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);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question