Promise all map update array
Found what was wrong, it seems you can't add a property which does not exist in my mongoose model User
. To bypass it I did:
let updatedUser = user.toObject();updatedUser.hasCar = !!car;return updatedUser;
Thanks everyone
It seems to work as it is. I made some simple changes to fake out Car.count
and removed ObjectId
, and it works as expected:
const cars = {1: ['car a', 'car b'], 3: ['car c']};const Car = { count: (user) => new Promise((resolve, reject) => setTimeout(() => resolve(cars[user.userId]), 1000))};function findCars(users) { return Promise.all(users.map((user) => Car.count({ userId: user._id }) .then((car) => { user.hasCar = !!car; return user; }) )) .then(console.log);}const users = [{_id: 1}, {_id: 2}, {_id: 3}];findCars(users);
This returns a Promise, and one second later logs the following to the console:
[{"_id":1,"hasCar":true},{"_id":2,"hasCar":false},{"_id":3,"hasCar":true}]
Note, I originally used the simpler
count: (user) => Promise.resolve(cars[user.userId])
But I wanted to ensure some true async. Neither way had any issues.
You can see this in action on RunKit.