【发布时间】:2020-01-21 06:11:49
【问题描述】:
在使用填充方法而不是对象后,我的查询响应为 null
这是我的路由处理程序
router.get("/:id", (req, res, next) => {
let id = req.params.id;
Order
.findById(id)
.populate('product')
.exec()
.then(doc => res.status(200).json({
...doc._doc,
requests: {
method: "GET",
desc: "All Orders",
url: "http://localhost:3000/orders"
}
}))
})
这是我的架构
const mongoose = require("mongoose");
var orderSchema = {
_id: mongoose.Schema.Types.ObjectId,
product: {
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
required: true
},
quantity: {
type: Number,
default: 1
}
}
module.exports = mongoose.model('Order', orderSchema);
这是我在使用 populate() 后得到的示例响应。在使用填充之前,我得到了一个 OjectId,我检查了它是否存在于数据库中
{
"quantity": 1947,
"_id": "5e25af75362bb0538c37b587",
"product": null,
"__v": 0,
"requests": {
"method": "GET",
"desc": "All Orders",
"url": "http://localhost:3000/orders"
}
}
【问题讨论】:
-
在删除集合并再次创建它们之后它工作了。我不确定为什么会这样。我认为这是 mongoDb 的一些内部错误
标签: javascript node.js mongodb mongoose mongodb-query