首页 > 解决方案 > Mongoose:将对象推送到对象数组

问题描述

我已经查看了其他各种类似的问题,但似乎无法理解为什么我不能将只有 2 个数字的对象推送到数组中。

我尝试复制的示例如下: Mongoose findOneAndUpdate:更新对象数组中的对象 如何通过一次调用将对象数组推送到 mongoose 中的数组中? Mongoose .find 字符串参数

以及官方文档:https ://mongoosejs.com/docs/api.html#mongoosearray_MongooseArray-push

这是我的架构

const BatchSchema = new mongoose.Schema({

  title: {
    type: String,
    required: true,
    trim: true
  },

  envRecord: {
    type: [{
      tmp: {
        type: Number
      },
      hum: {
        type: Number
      }
    }],
  }

});

BatchSchema.plugin(timestamp);

const Batch = mongoose.model('Batch', BatchSchema);
module.exports = Batch;

我的推送代码如下所示:

 server.put('/batches/:title', async(req, res, next) => {
    //Check for JSON
    if (!req.is('application/json')) {
      return next(new errors.InvalidContentError("Expects 'application/json'"));
    }

    try {
      const batch = await Batch.findOneAndUpdate(
        { _title: req.params.title },
        req.body,
        batch.envRecord.push({ tmp, hum })
      );
      res.send(200);
      next();
    } catch(err) {
      return next(new errors.ResourceNotFoundError(`There is no batch with the title of ${req.params.title}`));
    }
  });

使用邮递员我正在使用 PUT 在正文中发送以下 JSON

http://xxx.xx.xx.xxx:3000/batches/titleGoesHere
{
    "tmp": 20,
    "hum": 75
}

我有点困惑的是,我发现的所有示例都在使用$push,但官方文档似乎不再有,而是在使用MongooseArray.prototype.push(),这就是为什么我试图引用我的batch.envRecord.push({ tmp, hum })

是的,我已经检查了标题是否匹配,并且可以找到批次

server.get('/batches/:title', async(req, res, next) => {

    try {
      const batch = await Batch.findOne({title: req.params.title});
      res.send(batch);
      next();
    } catch(err) {
      return next(new errors.ResourceNotFoundError(`There is no batch with the title of ${req.params.title}`));
    }
  });

标签: mongoosepushsubdocument

解决方案


batch.envRecord.push({ tmp, hum })作为第三个参数传递,findOneAndUpdate其中代表查询选项对象。findOneAndUpdate所以你只需要在执行之后推送对象save。这种方法的缺点是执行了 2 个查询:

const batch = await Batch.findOneAndUpdate(
  { title: req.params.title },
  req.body   
).exec();

batch.envRecord.push({ tmp, hum });
batch.save();

这就是为什么使用$push是首选方法的原因。


推荐阅读