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);
如上所述,是否仅仅是因为我没有正确导出或引用我的模型?还是别的什么?
潜在的注意事项
id
,即使 mongo 会生成一个,因为我的应用程序中其他不相关的东西的工作方式,所以我只是制作了我的“自己的”ID,称为 {{1} } 并使其类型为 id
ObjectId
或 reports
,但从来没有收到实际数据。提前致谢。