mongoose - 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}`));
}
});
解决方案
您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
是首选方法的原因。
推荐阅读
- android - Coinbase oauth 2.0 重定向 uri android
- node.js - MAC - NPM - VSTS - 将注册表和令牌插入全局 npmrc 文件
- docker - 访问在 Docker For Desktop 中本地运行的 Kubernetes 服务?
- dialog - 显示工作表时,NSheet 控制器不会运行。
- html - 使用 flexbox 将我的徽标设置在左侧,将导航菜单设置在右侧
- python - Keras 模型溢出未知错误 | (IndexError:列表索引超出范围)
- elasticsearch - 在嵌套对象中追加数据
- regex - 从一个元素中获取文本,在另一个元素中显示
- c# - 将登录页面添加到 Swagger
- mysql - 占用所有 CPU 的 ubuntu .syslogs 后台进程