简体   繁体   中英

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

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!

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);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM