【发布时间】:2019-02-20 23:17:11
【问题描述】:
如何使用自己的 _id 访问对象数组并使用 Mongo/Mongoose 对其进行更新?
查看我的更新查询并检查是否有问题,因为此代码没有返回任何错误,但它并没有真正更新该字段
modelUser.findOneAndUpdate(
{ userName: body.author, "portfolio._id": body.id },
{ new: true },
{
$set: { //I thing the problem it's over here
"portfolio.$.profitLoss": profitLoss,
"portfolio.$.percentage": percentage
}
},
(err, user) => {
if (err) {
console.log(err);
}
console.log(`Done`);
}
);
这是我的用户架构:
const userSchema = new Schema({
...stuff,
portfolio: [
{
coin: String,
amount: String,
price: String,
bought: Date,
profitLoss: String,
percentage: String
}
],
});
基本上我认为 mongo 只是不知道这些子文档中的哪些应该更新,我不知道是否有类似 findOneAndUpdate 的子对象/文档的 id。
【问题讨论】:
-
架构组合中没有 _id 字段。如果添加 id 字段,查询应该可以工作。
-
@SergiNadal 如果您不指定 _id 是什么,则默认添加它并自行创建?还是我错了?
-
我不确定,我想不是!你可以很容易地检查它,在 mongo shell 中找到一个文档并浏览它,你会看到数组是否有一个 _id 字段。我通常使用 Roto 3T,在 mongo 集合中搜索,robomongo.org
标签: javascript arrays mongodb mongoose nosql