Я не хочу вставлять новый документ в MongoDB, если не найдено подходящих данных.
findOneAndUpdate () не работает. Он выдает ошибку во время выполнения, говоря: «Не удается прочитать свойство 'firstField' со значением NULL"
Моя схема выглядела так:
const mongoose = require("mongoose");
const TestSchema = mongoose.Schema(
{
firstField: {
type: String,
required: true,
unique: true,
sparse: true
},
secondField: {
type: [String],
required: true
}
);
module.exports = mongoose.model("Test", TestSchema);
Мой запрос выглядел так:
Test.findOneAndUpdate(
{
secondField: { $in: req.body.second }
},
{ $set: { firstField: req.body.first } },
{ new: true },
(err, test) => {
if (err) {
console.log("There are no matching first fields");
console.log(err);
}
console.log("Field updated successfully");
});