【发布时间】: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