简体   繁体   中英

Issues populating mongoose document after model query

First time on SO so I'm hoping this goes well.

I'm using Mongoose on a current project and until now I haven't had any issues. 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.

I'm working on a simple authentication route. My client document is broken into two object references, login and user profiles. 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. 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

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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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