I can't manipulate the Mongoose results after populate()

node.js mongodb mongoose lodash

102 观看

1回复

517 作者的声誉

I have the following query, I'm using Mongoose and Lodash:

Book
  .find()
  .pupulate({
    path: 'authors.profile', // find all books and populate the authors.profile field
    select: 'name'
  })
  .exec()
  .then(function(books, err){
    // log books at this point
    console.log('books before', books);
    // extract the data from inside 'profile' and replace the 'profile' itself
    _.each(books, function(book){
      book.authors = _.map(book.authors, 'profile');
      // log books at this point --> it works!
      console.log('books during', books);
    });
    // log books at this point --> loop is gone :(
    console.log('books after', books);
  });

// log before

books before [{
  _id: 5a32c3650e3db321fc7eb0c7,
  name: 'Moby Dick',
  authors: [{
    profile: {
      _id: 5a32dd7bf6807021bbe2f083,
      name: 'Herman Melville'
    }
  },{
    profile: {
      _id: 5a439db1e5d4f0182088964b,
      name: 'Richard Bentley'
    }
  }]
}]

// log during the loop (this is the desired output)

books during [{
  _id: 5a32c3650e3db321fc7eb0c7,
  name: 'Moby Dick',
  authors: [{
    _id: 5a32dd7bf6807021bbe2f083,
    name: 'Herman Melville'
  },{
    _id: 5a439db1e5d4f0182088964b,
    name: 'Richard Bentley'
  }]
}]

// log after (reverts back to the initial data before the loop)

books after [{
  _id: 5a32c3650e3db321fc7eb0c7,
  name: 'Moby Dick',
  authors: [{
    profile: {
      _id: 5a32dd7bf6807021bbe2f083,
      name: 'Herman Melville'
    }
  },{
    profile: {
      _id: 5a439db1e5d4f0182088964b,
      name: 'Richard Bentley'
    }
  }]
}]

Why does that happen and how can I log the desired output after the loop?

Thanks!

作者: trs 的来源 发布者: 2017 年 12 月 27 日

回应 1


1

517 作者的声誉

Looks like I need to use lean() before I can manipulate the results:

Book
  .find()
  .populate({
    path: 'authors.profile', // find all books and populate the authors.profile field
    select: 'name'
  })
  .lean() // <-------------
  .exec()
  .then(function(books, err){
    console.log('books before', books);
    _.each(books, function(book){
      book.authors = _.map(book.authors, 'profile');
      console.log('books during', books);
    });
    console.log('books after', books);
  });
作者: trs 发布者: 2017 年 12 月 27 日
32x32