Обновите документ, если он есть, иначе не вставляйте документ в MongoDB - PullRequest
0 голосов
/ 11 ноября 2019

Я не хочу вставлять новый документ в 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");
});

1 Ответ

0 голосов
/ 11 ноября 2019

Вы можете использовать фильтр и обновление, а затем с UpdateOne. Например,

var collection = db.GetCollection<BsonDocument>("Collection name");

var filter = Builders<BsonDocument>.Filter.Eq("the field you want to filter by","the value of the field");
var update = Builders<BsonDocument>.Update.Set("the field you want to update","value")
collection.UpdateOne(filter, update);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...