【发布时间】:2018-08-28 13:43:11
【问题描述】:
这是我的 user 和 product 架构:
const productSchema = new Schema({
//...
addedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "users"
}
});
const userSchema = new Schema({
//...
addedItems: [{
type: mongoose.Schema.ObjectId,
ref: "products"
}]
});
mongoose.model("products", productSchema);
mongoose.model("users", userSchema);
在我的 Node 后端路由中,我执行以下查询:
User.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { addedItems: newProduct._id } },
{ upsert: true, new: true },
function(err, doc) {
console.log(err, doc);
}
);
console.log 打印出这个:
{
//...
addedItems: [ 5ab0223118599214f4dd7803 ]
}
一切看起来都不错。我去实际使用我的 mongo db 的前端网站查看数据;我正在使用mlab.com,这就是显示的内容:
{
//...
"addedItems": [
{
"$oid": "5ab0223118599214f4dd7803"
},
{
"$oid": "5ab0223118599214f4dd7803"
}
]
}
问题:到底发生了什么?为什么它会在 addedItems 中添加一个额外的条目?!即使我的 console.log 只显示了一个。
注意:
我测试了后端路由是否被多次调用。它不是。
$push 似乎有问题,因为如果我只有{ addedItems: newProduct._id },那么只有一个条目进入,但它会覆盖整个数组。
编辑:
制作了一个测试项目以产生相同的结果:https://github.com/philliprognerud/test-mcve-stackoverflow
谁能弄清楚发生了什么?
【问题讨论】:
-
也许你最终会调用它两次?
-
@Johnny 我很确定我不会两次调用“findOneAndUpdate”。我处理的代码也不多。所以我想知道这怎么可能发生。另外,由于我正在执行“new: true”,因此它应该返回最新的文档。而且它只显示一个。
-
在更新之后我唯一要做的就是调用 res.send(...) ,它会回到我的 React 前端。请记住,这只会发生在“$push”中,如果我尝试只执行“{ addedItems: newProduct._id }”,那么只有一个条目会进入。但它显然会覆盖所有内容。
标签: node.js database mongodb mongoose mongoose-schema