我有以下查询,我正在使用Mongoose和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);
});
//在
之前登录books before [{
_id: 5a32c3650e3db321fc7eb0c7,
name: 'Moby Dick',
authors: [{
profile: {
_id: 5a32dd7bf6807021bbe2f083,
name: 'Herman Melville'
}
},{
profile: {
_id: 5a439db1e5d4f0182088964b,
name: 'Richard Bentley'
}
}]
}]
//循环期间记录(这是所需的输出)
books during [{
_id: 5a32c3650e3db321fc7eb0c7,
name: 'Moby Dick',
authors: [{
_id: 5a32dd7bf6807021bbe2f083,
name: 'Herman Melville'
},{
_id: 5a439db1e5d4f0182088964b,
name: 'Richard Bentley'
}]
}]
// log after(恢复到循环前的初始数据)
books after [{
_id: 5a32c3650e3db321fc7eb0c7,
name: 'Moby Dick',
authors: [{
profile: {
_id: 5a32dd7bf6807021bbe2f083,
name: 'Herman Melville'
}
},{
profile: {
_id: 5a439db1e5d4f0182088964b,
name: 'Richard Bentley'
}
}]
}]
为什么会发生这种情况?如何在循环后记录所需的输出?
谢谢!
答案 0 :(得分:1)
在我操作结果之前,我似乎需要使用lean()
:
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);
});