简体   繁体   English

在 model 查询后填充 mongoose 文档的问题

[英]Issues populating mongoose document after model query

First time on SO so I'm hoping this goes well.第一次上SO,所以我希望一切顺利。

I'm using Mongoose on a current project and until now I haven't had any issues.我在当前项目中使用 Mongoose,直到现在我还没有遇到任何问题。 As the title states, after querying for a document and verifying that document actually exists in the database using a simple console.log, I can't get my document's object references to populate when I use the populate method.如标题所述,在使用简单的 console.log 查询文档并验证该文档确实存在于数据库中之后,当我使用填充方法时,我无法获取要填充的文档的 object 引用。

I'm working on a simple authentication route.我正在研究一个简单的身份验证路线。 My client document is broken into two object references, login and user profiles.我的客户文档分为两个 object 参考,登录和用户配置文件。 In my query I'm searching for a client document where the login profile object reference id matches a previously queried login profile's id.在我的查询中,我正在搜索一个客户端文档,其中登录配置文件 object 参考 ID 与先前查询的登录配置文件的 ID 匹配。 Then I want to populate both the user profile and login profile on the client document, then return the client document.然后我想在客户端文档上填充用户配置文件和登录配置文件,然后返回客户端文档。

My console log is showing the client document but the population methods don't seem to be executing.我的控制台日志显示客户端文档,但填充方法似乎没有执行。 Code is below.代码如下。

const login = await LoginProfile.findOne({ email });
  if (login === null) {
    console.log("Account doesn't exist.");
  } else {
    let validPassword = await bcrypt.compare(password, login.password);
    if (!validPassword) {
      console.log("Email or Password is incorrect");
    } else {
      const clientDoc = await Client.findOne({
        loginProfile: login,
      });

      console.log(clientDoc.populate("userProfile").populate("loginProfile");
    }
  }

I'm probably doing this all wrong but I'm self taught and I'm trying.我可能做这一切都错了,但我是自学的,我正在努力。 Thanks for whatever solutions you may have.感谢您提供的任何解决方案。 If you have other ways of implementing this, please share!如果您有其他实现方式,请分享! Thanks!谢谢!

Welcome to Stack Overflow, MrGeonDeaux欢迎来到 Stack Overflow,MrGeonDeaux

Instead of:代替:

console.log(clientDoc.populate("userProfile").populate("loginProfile"));

You could populate the documents on finding, here's the full snippet:您可以在查找时填充文档,这是完整的片段:

const login = await LoginProfile.findOne({ email });
if (login === null) {
  console.log('Account doesn\'t exist.');
} else {
  const validPassword = await bcrypt.compare(password, login.password);
  if (!validPassword) {
    console.log('Email or Password is incorrect');
  } else {
    const clientDoc = await Client.findOne({
      loginProfile: login
    }).populate('userProfile loginProfile');

    console.log(clientDoc);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM