You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The text was updated successfully, but these errors were encountered:
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
@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();
});
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 .
"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();
});`
The text was updated successfully, but these errors were encountered: