1

I'm using nodejs and mongoose in my project and i'm trying to populate an array of object(truc in my case) using mongoose populate but i got an empty array in the truc attribute I dont know why :

function :

    const getUserVehicles = async(id) =>{
    return new Promise((resolve, reject) => {
      User.findById(id)
      .populate('truc')
      .exec(function (err, item) {
        if (err) return handleError(err);
        console.log('The item is %s', item);
        // prints "The author is Ian Fleming"
        resolve(item)
      });
    })
  }

response :

   "verified": false,
   "userType": "Individu",
   "status": "Disponible",
   "truc": [], --here's the empty array
   "_id": "5d4435f57cd101243d1b48a6",
   "email": "test125@gmail.com",

   "createdAt": "2019-08-02T13:09:09.148Z",
   "updatedAt": "2019-08-02T13:09:09.148Z"

User model :

.....
  truc: [{ type: Schema.ObjectId, ref: 'Vehicle' }]
.....

could anyone help please ?

Dvyn Resh
  • 980
  • 1
  • 6
  • 14

2 Answers2

0

change truc type from Schema.ObjectId to Schema.Types.ObjectId and mongoose v >= 5 supports promises so you can do

const getUserVehicles = id => User.findById(id).populate('truc');

and then call it

getUserVehicles(/* id */)
  .then(console.log)
  .catch(console.log);
Asaf Aviv
  • 11,279
  • 1
  • 28
  • 45
  • Unrelated, but passing raw `console.log` as a callback won't work because it's being executed in the wrong context, you will need to pass `console.log.bind(console)` instead: https://stackoverflow.com/questions/28668759/what-does-this-statement-do-console-log-bindconsole – m90 Aug 02 '19 at 15:05
  • thnaks for ur answer but I got the same issue, truc array is empty –  Aug 02 '19 at 15:11
  • I want to use the asyn / await functions –  Aug 02 '19 at 15:11
  • @titilo Are you sure there is ids in `truc` ? post the returned document without populate. If you just return a promise and `findById` already returns a promise there is no reason to use an `async function` – Asaf Aviv Aug 02 '19 at 15:14
  • Yes there are ids in the tric Object, but I still get an empty array –  Aug 05 '19 at 08:21
0

I confirm having a similar issue for mongoose higher than @5.6.7 (both in async and calllback pattern approaches). Still looking around for a fix.

Some suggestions have been made to use populate virtuals instead of having a huge array of objectId references.

vmk
  • 31
  • 1
  • 3