尝试将键:值对添加到res.locals.object不起作用节点/快速

问题描述

我正在尝试使用res.locals中间件通过多个MongoDB操作来构建next()对象。

一旦我向res.locals添加一个对象,例如:res.locals.newObject,接下来我想向{key: values}添加更多newObject

赞:

for(let i=0; i<res.locals.surveys.length; i++){
    await Answer.countDocuments({question_oid: {$in: res.locals.surveys[i].questions}).then((result) => {

        res.locals.surveys[i]["count_answers"] = result;
    })
}

我稍后检查了该对象,它没有键或值。

我也这样尝试过:

        res.locals.surveys[i].count_answers = result;

但是那也不起作用。 res.locals对象有技巧吗?

解决方法

除非使用async / await,否则不能将for循环与异步调用一起使用。我建议您进一步了解异步代码及其含义。在线上有大量资源。 https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing

如果您使用异步等待,请按以下方式更改代码。

const result = await Answer.countDocuments({question_oid: {$in: res.locals.surveys[i].questions});
res.locals.surveys[i]["count_answers"] = result;