【问题标题】:push object to an array within multiple loops将对象推送到多个循环内的数组
【发布时间】:2021-06-14 09:46:52
【问题描述】:

我有一个像 [ { category: 'xxx' }, { author: '12345' } ] 这样的对象数组。我的任务是搜索这个数组并在 mongoDB 中找到返回 _id [ { category: '_id' }, { author: '_id' } ]

我有执行此操作的代码,我创建了一个空数组arrSearch,当它找到_id 时,它将推送到该数组。但是运行之后,数组是空的,没有推送数据。我不确定它有什么问题。

export const getObjIdFromCondition = async (conditionArr) => {
    var arrSearch = []

    try {
        await conditionArr.map(obj => {
            for (let key in obj) {
                switch (key) {
                    case 'category':
                        const foundCategory = Category.findOne({ slug: obj[key] }).orFail()
                        foundCategory.then(resp => arrSearch.push({category: resp._id})) // push obj to array
                        break
                    case 'author':
                        const foundAuthor = Author.findOne({ author_id: obj[key] }).orFail()
                        foundAuthor.then(resp => arrSearch.push({ author: resp._id }))
                        break
                    default:
                        break
                }
            }
        })
    } catch (error) {
        console.log(error);
    }
    console.log('arrSearch', arrSearch) // -> empty array
}

你能帮帮我吗?提前谢谢你。

【问题讨论】:

  • 您的数据库查询也需要同步,否则map 函数将在不等待获取数据的情况下返回,并且您的 arrSearch 将在没有数据的情况下记录

标签: javascript node.js arrays mongodb mongoose


【解决方案1】:

我尝试使用 promise all 并且它有效。

export const getObjIdFromCondition = async (conditionArr) => {
    try {
        var arrSearch = await Promise.all(
            conditionArr.map(async (obj) => {
                for (let key in obj) {
                    switch (key) {
                        case 'category':
                            const foundCategory = await Category.findOne({ slug: obj[key] })
                            return { category: foundCategory._id }
                        case 'author':
                            const foundAuthor = await Author.findOne({ author_id: obj[key] })
                            return { author: foundAuthor._id }
                        default:
                            break
                    }
                }
            })
        )
    } catch (error) {
        console.log(error)
    }
    console.log("arrSearch", arrSearch)
}

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 2014-11-12
    • 2017-02-02
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多