【发布时间】:2022-08-17 18:27:58
【问题描述】:
据我所知,populate() 在我的代码中被调用(因为如果我给它一个错误的路径,我会得到一个错误),但它似乎没有做任何事情。
我在 Stack Overflow 中搜索了过去的问题,但我没有看到有人使用引用自身的模型,所以我的猜测是这可能是问题所在。
这个Mongoose doc 是我阅读如何使用populate() 的地方。
我的模特
const mongoose = require(\'mongoose\');
const schema = new mongoose.Schema({
firstName: { type: String },
lastName: { type: String },
email: { type: String, unique: true },
teamLeaders: [{ type: mongoose.Schema.Types.ObjectId, ref: \'Agent\' }],
teamMembers: [{ type: mongoose.Schema.Types.ObjectId, ref: \'Agent\' }]
});
let Agent = mongoose.model(\'Agent\', schema);
Agent.init();
module.exports = Agent;
MongoDB Atlas 中的实际文档(匿名名称 + 电子邮件)
{
\"_id\": {
\"$oid\": \"62e3e0ab57560a5c15a535e0\"
},
\"teamLeaders\": [],
\"teamMembers\": [
{
\"$oid\": \"62e3f548678dbed5593acc8e\"
},
{
\"$oid\": \"62e3f548678dbed5593acc91\"
},
{
\"$oid\": \"62e3f548678dbed5593acc94\"
},
{
\"$oid\": \"62e3f548678dbed5593acc97\"
},
{
\"$oid\": \"62e3f548678dbed5593acc9a\"
},
{
\"$oid\": \"62e3f548678dbed5593acc9d\"
},
{
\"$oid\": \"62e3f548678dbed5593acca0\"
},
{
\"$oid\": \"62e3f548678dbed5593acca3\"
}
],
\"firstName\": \"John\",
\"lastName\": \"Smith\",
\"email\": \"john@smith.com\",
\"__v\": 8
}
我调用 populate() 的代码
const Agent = require(\'../models/agents\');
const mongoose = require(\"mongoose\");
const db = require(\"../config/db\");
mongoose.connect(process.env.MONGODB_URI || db.url);
// I\'ve removed other functions that are not related to this. And the DB connection is definitely working fine.
// Actual private function in my code.
async function addAgent(firstName, lastName, email, isTeamLeader, teamLeader) {
let newAgent = Agent();
newAgent.firstName = firstName;
newAgent.lastName = lastName;
newAgent.email = email;
if (isTeamLeader) {
await newAgent.save();
} else {
newAgent.teamLeaders.push(teamLeader);
let savedAgent = await newAgent.save();
teamLeader.teamMembers.push(savedAgent);
await teamLeader.save();
}
}
// This is a dummy function to show how I created the agents.
async function createAgents() {
await addAgent(\'John\', \'Smith\', \'john@smith.com\', true, null);
// Some time later... I called addAgent() manually since this is for an internal team with only 30 people.
// It\'s also why I\'m just querying for the firstName since there\'s only one John in the internal team.
let teamLeader = await Agent.findOne({ firstName: \'John\' });
await addAgent(\'Peter\', \'Parker\', \'peter@parker.com\', false, teamLeader);
}
// This is the main one where I try to call populate().
async function mainFunction() {
Agent.findOne({ firstName: \'John\' }).populate({ path: \'teamMembers\', model: \'Agent\' }).exec((err, agent) => {
if (err) return handleError(err);
console.log(\'Populated agent: \' + agent);
});
}
-
您是否检查过您是否有多个带有
firstName: Sam的文档?findOne将返回它找到的第一个匹配项。 -
@NeNaD 是的,只是仔细检查了一下,我的数据库中肯定只有一个。我还附加了一个调试器来检查
findOne结果,它与我在数据库中查看的结果完美匹配,包括对象ID。 -
你所说的“但它似乎什么也没做。”是什么意思。你的
console.log()的结果是什么?您使用的是哪个版本的猫鼬? -
@Weedoze然而,我刚刚意识到问题:1.我完全误解了
populate()所做的文档。我认为它会使用填充的结果更新实际文档,但它所做的只是执行第二次查询,因此我可以在运行时访问孩子的属性。 2.populate()正在做它的事情,但由于某种原因,exec()中的回调不起作用。如果我删除回调(即只使用exec())并等待承诺,那么一切都很好。只需使用populate()甚至then(callback)也可以。诡异的! -
@jon2512chua:太好了 - 请发布您的答案并将其标记为您问题的答案,以供未来的观众使用
标签: javascript node.js mongodb mongoose