gpt4 book ai didi

javascript - 如何在 2 个映射函数中等待并从 mongoDB 中检索文档

转载 作者:行者123 更新时间:2023-12-04 08:10:52 25 4
gpt4 key购买 nike

我需要对返回如下内容的 API 进行一些修改:

[
{
"_id": "0000000000000000001",
"name": "Random name",
"categories": [
"5eb8548330550e017f8902e6",
"5eb2548630550e117f8909eb",
"5eb6548930550e017f8909e9"
]
},
{...},
]
每个结果的类别作为其各自文档的 id 返回。
我需要操作结果,以便每个对象的类别字段都有一个对象数组,每个对象都有其类别的 id 和名称。
我举了一个结果应该是什么的例子:
[
{
"_id": "0000000000000000001",
"name": "Random name",
"categories": [
{"_id": "5eb8548330550e017f8902e6",
"name": "Category 1"},
{"_id": "5eb2548630550e117f8909eb",
"name": "Category 2"},
{"_id": "5eb6548930550e017f8909e9",
"name": "Category 3"},
]
},
{...},
]
我需要使用普通的 JS 来做到这一点,到目前为止,这就是我所做的,但它返回一个未定义的数组:
const resultArray = await Promise.all(
searchResults.map(async (item) => {
item.categories.map(async (categoryId) => {
return await CategoryType.find({ _id: categoryId});
});
})
);
目前,我正在尝试为类别字段中的每个 id 获取每个类别文档。
我敢打赌,我得到一个 undefined 数组的原因是我以错误的方式处理异步,但不知道如何处理。

最佳答案

严格回答您的问题:您缺少同步(因为 Array.prototype.map 'ignores' async):

const resultArray = await Promise.all(
searchResults.map(async (item) => {
const promises = item.categories.map(async (categoryId) => {
// you dont want find, but findOne btw
return await CategoryType.findOne({ _id: categoryId});
});
const categories = await Promise.all(promises)
item.categories = categories
return item
})
);
这可以简化为
const resultArray = await Promise.all(
searchResults.map(async item => {
item.categories = await Promise.all(item.categories.map(categoryId => {
return CategoryType.findOne({ _id: categoryId})
}))
return item
})
);
但正确的做法很可能是使用 填充
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/dummy')

const Category = mongoose.model('Category', {
name:String,
}, 'categories');
const X = mongoose.model('X', {
name:String,
categories: [{type: mongoose.Types.ObjectId, ref: 'Category'}]
}, 'xs');

;(async()=>{
try {
mongoose.set('debug', true)

const xs = await X.find().populate('categories')

console.log('xs : ', xs[0])
} finally {
mongoose.disconnect()
}
})()
顺便说一下,你会注意到 Mongoose 在引擎盖下使用 find({ _id: {$in:[]}})只发出一个请求(比做多个请求更好) findOne (像你一样做)

关于javascript - 如何在 2 个映射函数中等待并从 mongoDB 中检索文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65967168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com