【问题标题】:Mongoose: Pushing an object to an array of objectsMongoose:将对象推送到对象数组
【发布时间】:2019-04-08 08:45:24
【问题描述】:

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

我尝试复制的示例如下: Mongoose findOneAndUpdate: update an object in an array of objects How to push an array of objects into an array in mongoose with one call? Mongoose .find string parameters

还有官方文档: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}`));
    }
  });

【问题讨论】:

    标签: mongoose push subdocument


    【解决方案1】:

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

    const batch = await Batch.findOneAndUpdate(
      { title: req.params.title },
      req.body   
    ).exec();
    
    batch.envRecord.push({ tmp, hum });
    batch.save();
    

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

    【讨论】:

    • 所以$push 不是猫鼬中的东西,而是其他东西的一部分?在这种情况下会怎样?我曾多次尝试过,但没有成功。假设这些示例来自 2014/2015 年,所以语法可能从那时起发生了变化?
    猜你喜欢
    • 1970-01-01
    • 2018-07-20
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    相关资源
    最近更新 更多