Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue while creating new tour with "guide" array users id #195

Open
Youtta opened this issue May 15, 2023 · 1 comment
Open

Issue while creating new tour with "guide" array users id #195

Youtta opened this issue May 15, 2023 · 1 comment

Comments

@Youtta
Copy link

Youtta commented May 15, 2023

"message": "Cannot read properties of undefined (reading 'map')", "stack": "TypeError: Cannot read properties of undefined (reading 'map')\n at model.<anonymous> (C:\\Users\\abdua\\Downloads\\complete-node-bootcamp-master\\complete-node-bootcamp-master\\4-natours\\starter2\\models\\tourModel.js:128:38)\n at callMiddlewareFunction

in tourModel, I have also added:
guides: Array

`tourSchema.pre('save', async function(next) {
console.log(this.guides); --> undefined
const guidesPromises = this.guides.map(async id => await User.findById(id));
this.guides = await Promise.all(guidesPromises);
next();

});`

@Youtta Youtta changed the title Issue while creating new tour with "guide" array id users id Issue while creating new tour with "guide" array users id May 15, 2023
@SoumyaSubhrajit
Copy link

@Youtta you're trying to access this.guides.map(...) within the pre('save', ...) middleware function of your tourSchema. The error is indicating that this.guides is undefined at the time the map function is called.

To resolve this issue, you need to make sure that this.guides is defined before attempting to use the map function. One way to do this is by initializing this.guides as an empty array if it is undefined.

Here what you can do here.

tourSchema.pre('save', async function(next) {
  console.log(this.guides); // undefined
  this.guides = this.guides || []; // Initialize guides as an empty array if undefined
  const guidesPromises = this.guides.map(async id => await User.findById(id));
  this.guides = await Promise.all(guidesPromises);
  next();
});
  1. When you trying to iterate for something is empty/undefined it will gave you undefined remember that guides have some value to iterate on.

Check and if it okay then good otherwise we might be looking to something else .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants