【发布时间】:2020-07-31 02:52:20
【问题描述】:
我的用户架构是这样的
{
_id:ObjectId("6e9465528a15ba6")
name: 'XYZ',
email: 'abc@gmail.com',
transactions: [
{
_id:ObjectId("5e946557a5128a15ba6"),
date: 2020-04-09T06:00:30.000Z,
type: 'type1',
category: 'category1',
description: 'some desc',
}
]
}
我想用特定的 id 更新一些交易字段。但没有发生。
我尝试了回答的解决方案 Mongoose, update values in array of objects这个问题。
可能是我的_id 是ObjectId 类型并且来自我的请求的id 是字符串?
那么我该如何解决这个问题呢?
我的代码是这样的,但仍然出现错误user.transactions._id is not function
app.post('/api/update', function (req, res) {
const {
id,
email,
date,
type,
category,
description
} = req.body;
User.findOne({email}, function (err, user) {
if (err) {
console.error(err);
res.status(500)
.json({
error: 'Internal error please try again'
});
} else if (!user) {
res.status(401)
.json({
error: 'Incorrect email or password'
});
} else {
const objectId = mongoose.Types.ObjectId(id);
let transaction = user.transactions._id(objectId);
transaction.date = date;
transaction.type = type;
transaction.category = category;
transaction.description = description;
user.save((err, data) => {
if (err) return res.send(err);
return res.sendStatus(200);
});
}
});
});
【问题讨论】:
-
我试过了,但似乎不起作用。请查看我有问题编辑的代码。
-
请求中的
id是transactions._id吗?或_id用于文档?如果是针对transactions._id,那么即使给定电子邮件存在文档,对于给定id,什么id 不存在事务对象? -
它的交易ID。
标签: node.js mongodb express mongoose mongodb-query