首页 > 解决方案 > Mongoose Populate 返回空数组 - 范围问题

问题描述

SO上有一些与此相关的问题,但到目前为止我还没有找到解决方案。

我将解释我的目标,然后布置我的文件。

我在这里有一个简单的用户查找:

let doc = await User.findOne({ _id: req.query.id })
   .select("stripeCustomer planLevel reports")

如您所见,我正在尝试使用报告数组返回我的用户,并且正如预期的那样,这将reports: [ 604faf2665cf4a2728750d9d, 604fb1c5d40744307002c8c8 ],作为响应的一部分返回。

然后我.populate("reports")像这样添加

let doc = await User.findOne({ _id: req.query.id })
   .select("stripeCustomer planLevel reports")
   .populate("reports");

现在我得到reports: [],了回应。

我相信我遇到了范围界定错误,但我似乎无法弄清楚,我将解释我现在拥有的所有文件;

主要app.js,除其他外,具有所有相关的要求

mongoose.promise = global.Promise;
require("./models/user");
require("./models/serp");
const getUserRoute = require("./routes/fetchUser/fetchUser");
app.use("/user", getUserRoute);

然后,我们使用fetchUser.js进入该/user路线,这是(除其他外)原始逻辑所在的位置,我再次删除了很多内容以保持相关性:

const mongoose = require("mongoose");
const User = mongoose.model("User");
const Serp = mongoose.model("Serp");

let doc = await User.findOne({ _id: req.query.id })
   .select("stripeCustomer planLevel reports")
   .populate({ path: "reports", model: "Serp" });

现在user.js(用户模式)(包含我们感兴趣的底部报告数组)

var mongoose = require("mongoose");
var UserSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      lowercase: true,
      required: [true, "can't be blank"],
      match: [/\S+@\S+\.\S+/, "is invalid"],
      unique: true,
    },
    hash: String,
    salt: String,
    stripeCustomer: String,
    stripeSubscription: String,
    subscription: Boolean,
    planLevel: String,
    reports: [{ type: mongoose.Types.ObjectId, ref: "Serp" }],
  },
  { timestamps: true }
);

mongoose.model("User", UserSchema);

然后我有serp.js(Serp Schema)(我称之为serp,但这些是报告,例如它们是serp的报告)

const mongoose = require("mongoose");
const { Schema } = mongoose;

const serpSchema = new Schema(
  {
    id: mongoose.Types.ObjectId,
    searchTerm: String,
    totalResults: Number,
    organicResults: Number,
  },
  { timestamps: true }
);

mongoose.model("Serp", serpSchema);

如前所述,仅仅是因为我没有正确导出或引用我的模型吗?或者是别的什么?

潜在的注意事项

提前致谢。

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


推荐阅读