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

Javascript 如何在2个映射函数中等待并从mongoDB检索文档,javascript,mongodb,asynchronous,mongoose,async-await,Javascript,Mongodb,Asynchronous,Mongoose,Async Await,我需要对返回如下内容的API进行一些修改: [ { "_id": "0000000000000000001", "name": "Random name", "categories": [ "5eb8548330550e017f8902e6", "5eb2548630550e117f8909eb",

我需要对返回如下内容的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});
    });
  })
);
目前,我正在尝试获取categories字段中每个id的每个category文档。
我敢打赌,我得到一个未定义数组的原因是,我以错误的方式处理异步,但无法弄清楚如何处理。

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

这可以简化为

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

顺便说一句,你会注意到,猫鼬在引擎盖下使用了
find({u id:{$in:[]}}})
,它只发出一个请求(比多次
findOne
(像你一样)

完美!非常感谢你
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()
  }
})()