【问题标题】:TypeError: utils.populate: invalid path. Expected string. Got typeof `undefined`类型错误:utils.populate:路径无效。预期的字符串。得到 typeof `undefined`
【发布时间】:2018-11-07 19:28:30
【问题描述】:

我正在尝试使用猫鼬的populate operator 来合并产品及其用户/所有者。

我制作了产品架构的“导出”模型,指定了所有字段,如下所示:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const someSchema= new Schema({
  something1: String,
  customers: [{ type: Schema.Types.ObjectId, ref: "customers" }],
  price: Number,
  ...
})
module.exports = mongoose.model("products", someSchema, "products");

我已设法将用户/所有者的_id 保存在产品中,它在 MongoDB Compass 中显示为橙色 "ObjectId('...')",并且此相同 ID 与“客户”集合中的用户匹配(手动查看) .

但是当我在另一个模块中运行搜索时:

  const model = require("../../models/productModel");
  model
    .populate("customers")
    .find({ < some fields> })
    .then( ... )
    .catch( ... )

它在控制台中抛出以下错误:

TypeError: utils.populate: invalid path. Expected string. Got typeof `undefined`

我在这里遗漏了什么吗?我试了将近一个小时,一无所获。对不起,如果我错过了一些重要的事情,我有点累了。

非常感谢任何帮助。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    我想通了。

    问题是我以错误的顺序拨打了populate

    我在打电话:

      model
        .populate("customers")
        .find({ < some fields> })
        .then( ... )
        .catch( ... )
    

    但它必须按以下顺序:

      model
        .find({ < some fields> })
        .populate("customers")
        .then( ... )
        .catch( ... )
    

    因为我们必须先find文件才能populate他们,否则就没有任何意义。

    为了以后参考,如果你只指定.populate("customers"),它不会填充所有的ID字段神奇地,你也必须指定哪个字段。你这样做:

    .populate({ path: "key_to_fill", model: "customers" })
    

    现在它将用customers 中的文档替换key_to_fill

    您可以在这里找到其他参数和选项:https://mongoosejs.com/docs/populate.html(官方文档)

    【讨论】:

      猜你喜欢
      • 2017-07-07
      • 2019-10-20
      • 1970-01-01
      • 2018-02-07
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多