[英]I can't manipulate the Mongoose results after populate()
我有以下查询,我正在使用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'
}]
}]
//在之后登录(返回到循环之前的初始数据)
books after [{
_id: 5a32c3650e3db321fc7eb0c7,
name: 'Moby Dick',
authors: [{
profile: {
_id: 5a32dd7bf6807021bbe2f083,
name: 'Herman Melville'
}
},{
profile: {
_id: 5a439db1e5d4f0182088964b,
name: 'Richard Bentley'
}
}]
}]
为什么会发生这种情况?循环后如何记录所需的输出?
谢谢!
看来我需要使用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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.