I'm having a problem where Mongodb findOne si not working in mapping throug array of object is returning [ Promise { } ]
const data = [
{
GLAccountId: 5fac4225dce5f459e40117f6,
Balance: 0
},
{
GLAccountId: 5fac4225dce5f459e401423,
Balance: 0
}
]
let glAccount= "";
let result = data.map(async(item) => {
glAccount = await GL_Account.findOne({ _id: item.GLAccountId});
return {
glAccount: glAccount.title,
balance: glAccount.balance
}
});
console.log(result);
can you guys help me with? Thanks.
Instead of iterating the data array and make multiple findOne calls, create a query from the array and use find()
or aggregate()
methods to make a single query with the custom projections as follows:
const data = [
{
GLAccountId: 5fac4225dce5f459e40117f6,
Balance: 0
},
{
GLAccountId: 5fac4225dce5f459e401423,
Balance: 0
}
]
const ids = data.map(item => item.GLAccountId)
let result = await GL_Account.find({ _id: { $in: ids } })
.lean()
.map(glAccount => ({
glAccount: glAccount.title,
balance: glAccount.balance
}))
or using aggregate()
:
let result = await GL_Account.aggregate([
{ $match: {
_id: { $in: ids.map(id => mongoose.Types.ObjectId(id)) },
} },
{ $project: {
_id: 0,
glAccount: '$title',
balance: 1
} }
]).exec()
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.