javascript - 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);
如前所述,仅仅是因为我没有正确导出或引用我的模型吗?或者是别的什么?
潜在的注意事项
- 我已经验证用户在报告数组中有条目,第一个返回也验证了这一点。
- 我的 serp.js 有一个
id
定义,即使 mongo 会生成一个,因为我的应用程序中其他不相关的东西的工作方式,所以我只是创建了我的“自己的”ID,调用id
并使其具有类型ObjectId
- 运行任何变体时,我从来没有收到错误,只是空的
reports
或reports
带有 ID 的,但从来没有实际数据。
提前致谢。
解决方案
推荐阅读
- android - 什么会导致 Activity 出现 kotlin.TypeCastException?
- python - Python While循环不迭代变量只打印命令
- android-studio - 我如何将 FutureBuilder 更改为 streambuilder 我需要在这里做什么?
- sql-server-2016 - 使用 SQL 从 JSON 数组中提取数据
- javascript - 在理解为什么它不切割我的字符串时遇到一些问题
- react-native - React Native:使用 React Navigation v5 创建 Switch Navigator
- python - Python 换行符 \n 在 jupyter 笔记本中不起作用
- python - nx.node_connectivity 和 nx.minimum_node_cut 不匹配
- python - 如何将包含日期的 csv 数据加载到 numpy 数组中?
- javascript - 跟踪数据库中添加的对象