【问题标题】:Mongoose populate() return null猫鼬填充()返回空
【发布时间】: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


【解决方案1】:

Mongoose populate 的行为类似于 SQL DB 中的左连接,这意味着如果没有找到外部文档,它将返回 null 或空数组。

因为也许您稍后将该字段添加到集合架构中,所以在以前的文档中该字段为空。

【讨论】:

  • 据我所知,我从未更改过架构。但是有什么办法可以交叉检查吗?
  • @AbhinavMani, mongoose/mongodb 没有对外部 ID 的验证,因此正确的方法是在插入(保存)之前自己验证外部 ID。你可以通过创建一个hook(middleware)来做到这一点。
猜你喜欢
  • 1970-01-01
  • 2016-04-28
  • 2023-03-21
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 2015-08-26
  • 1970-01-01
相关资源
最近更新 更多