mongodb - 两次更新查询将 ObjectID 添加到数组

标签 mongodb mongoose mongodb-query

我正在开发一个餐 table 规划应用程序,可以将客人分配到餐 table 。表格模型具有以下架构:

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

const tableSchema = new mongoose.Schema({
  name: {
    type: String,
    required: 'Please provide the name of the table',
    trim: true,
  },
  capacity: {
    type: Number,
    required: 'Please provide the capacity of the table',
  },
  guests: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Guest',
  }],
});

module.exports = mongoose.model('Table', tableSchema);

客人可以在App中拖放(使用React DND)来“表格”React组件。放在表上后,向 Node.js 方法发出 Axios POST 请求以更新数据库并将 guest 的对象 ID 添加到表模型中的数组中:

exports.updateTableGuests = async (req, res) => {
  console.log(req.body.guestId);
  await Table.findOneAndUpdate(
    { name: req.body.tablename },
    { $push: { guests: req.body.guestId } },
    { safe: true, upsert: true },
    (err) => {
      if (err) {
        console.log(err);
      } else {
      // do stuff
      }
    },
  );
  res.send('back');
};

这是按预期工作的,除了每个丢弃的 guest ,表模型的 guest 数组使用相同的 guest 对象 ID 更新两次?有谁知道为什么会这样?

我已尝试记录 req.body.guestID 以确保它是单个值并检查此函数是否未被调用两次。但这些测试都没有带来意想不到的结果。因此,我怀疑我的 findOneAndUpdate 查询有问题?

最佳答案

不要使用 $push这里的运算符,你需要使用$addToSet运算符代替...

The $push operator can update the array with same value many times where as The $addToSet operator adds a value to an array unless the value is already present.

exports.updateTableGuests = async (req, res) => {
  console.log(req.body.guestId);
  await Table.findOneAndUpdate(
    { name: req.body.tablename },
    { $addToSet : { guests: req.body.guestId } },
    { safe: true, upsert: true },
    (err) => {
      if (err) {
        console.log(err);
      } else {
      // do stuff
      }
    },
  );
  res.send('back');
};

关于mongodb - 两次更新查询将 ObjectID 添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50355473/

相关文章:

angularjs - Node res.render 更改 View 但不更改 url

javascript - 如何使用聚合和展开返回文档和子数组?

javascript - 根据字段数组大小分组并删除文档

java - 获取特定格式的mongo数据

javascript - Mongodb:如何返回查询列表中存在的数组元素

javascript - 无法理解复杂的 $group'ing/aggregation

mongodb - findById 和 load 之间的区别?

node.js - Post 请求永远不会被发出,只是发送 get

c# - 使用 C# 驱动程序从 MongoDB 集合上的文本查询中检索相关性有序结果

javascript - $在mongodb中过滤最多3层嵌套