类型错误:utils.populate:无效路径。预期字符串。得到 typeof `undefined`

Fus*_*ieb 1 mongoose mongodb

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

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

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");
Run Code Online (Sandbox Code Playgroud)

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

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

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

它在控制台中引发以下错误:

TypeError: utils.populate: invalid path. Expected string. Got typeof `undefined`
Run Code Online (Sandbox Code Playgroud)

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

任何帮助是极大的赞赏。

Fus*_*ieb 7

我想到了。

问题是我打电话populate的顺序不对。

我打电话给:

  model
    .populate("customers")
    .find({ < some fields> })
    .then( ... )
    .catch( ... )
Run Code Online (Sandbox Code Playgroud)

但它必须是这样的:

  model
    .find({ < some fields> })
    .populate("customers")
    .then( ... )
    .catch( ... )
Run Code Online (Sandbox Code Playgroud)

因为我们必须先把find文件整理好populate,否则没有任何意义。

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

.populate({ path: "key_to_fill", model: "customers" })
Run Code Online (Sandbox Code Playgroud)

现在它将替换key_to_fill为中找到的文档customers

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