javascript - 将属性添加到数组中 MongoDB 的对象并在响应中发送

标签 javascript node.js mongodb asynchronous async-await

我尝试使用下面的代码在 users 数组的元素(本例中为对象)中添加 quoteValue 键值。

当我打印 console.log(users[0]) 时,它没有显示 users[0]quoteValue 值。但是,console.log(users[0].quoteValue) 打印 quoteValue 的实际值。

我不明白这怎么可能。非常感谢您的帮助!

export async function get_client_users(req, res) {
    try {
        let users = await User.find({ role: { $eq: 'client' }, status: { $ne: 'deleted' } }, { name: 1, mobile: 1, email: 1, status: 1, ref_id : 1, _id: 1 });
        for(let i = 0; i < users.length; i += 1) {
            let quotes = await Quote.find({client: users[i]._id});
            const totalQuote = quotes.length;
            let cost = 0;
            for(let i = 0; i < quotes.length; i += 1) {
                cost += quotes[i].total_cost;
            }
            const result = {
                totalQuote: totalQuote,
                quoteValue: cost
            }

            Object.assign(users[i], result);
        }
        return res.status(200).json(users);
    } catch(e) {
        console.log(e);
        return res.status(400).json({ message: 'Technical Error. Please try again later.' });
    };
};

最佳答案

如果可以的话,我建议使用破坏( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment )来创建新的 users对象(在下面的代码中称为 updatedUsers),如下所示:

export async function get_client_users(req, res) {
    try {
        let users = await User.find({ role: { $eq: 'client' }, status: { $ne: 'deleted' } }, { name: 1, mobile: 1, email: 1, status: 1, ref_id : 1, _id: 1 });
        let updatedUsers = [];
        for(let i = 0; i < users.length; i++) {
            let quotes = await Quote.find({client: users[i]._id});
            let quoteValue = 0;

            for(let i = 0; i < quotes.length; i++) {
                quoteValue += quotes[i].total_cost;
            }

            updatedUser = {
                ...users[i],
                totalQuote: quotes.length,
                quoteValue
            }
            updatedUsers.push(updatedUser);
        }
        return res.status(200).json(updatedUsers);
    } catch(e) {
        console.log(e);
        return res.status(500).json({ message: 'An error occurred. Please try again later.' });
    };
};

我还更改了一些内容,例如发送 500而不是400当发生错误时,删除对 totalQuote 的分配变量通过分配 quotes.length直接联系updatedUser.totalQuote ,并且还使用了 i++而不是i += 1在你的for循环。我建议使用 ESLint ( https://eslint.org/ ) 或 Prettier ( https://prettier.io/ ) 等 linter 来提高代码的可读性。

此外,我建议使用 map ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map ) 迭代您的 users对象和reduce ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce ) 获取 quoteValue 的值来自total_cost您的属性(property)quotes ,但这超出了您的问题范围。

关于javascript - 将属性添加到数组中 MongoDB 的对象并在响应中发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59311055/

相关文章:

javascript - 如何替换特定字符之前的文本(正则表达式)

javascript - 聚合将文档键展开为新文档

javascript - Mongoose 不创建索引

node.js - NodeJS - Passport 登录时出现 404 错误

node.js - Node 脚本可执行文件在 Mac : env: node\r: No such file or directory 上不起作用

java - DDD Java with Spring - Repository 返回 Mono/Flux

javascript - 为什么函数上下文在实例化时会发生变化?

javascript - 在最后一个斜杠 (/) 后获取值

javascript - 尝试将我的应用程序发布到 Heroku 上时出现错误 :"No ' Access-Control-Allow-Origin' header 出现在请求的资源上”

javascript - 在命令行上运行 graphql 示例会导致意外的标记