首页 > 解决方案 > 用不同的值在 Mongoose 中更新多个文档——Express Js

问题描述

在为我的应用程序开发后端时,我遇到了一个问题。我使用 Mongoose 在后端运行 Express。我有一个用户模型,就像这样;

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    email: { type: String, required: true, unique: true, match: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ },
    username: { type: String, required: true, unique: true }, // using this one
    fullName: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    points: { type: Number, required: true }, // this one
    status: { type: String, require: true }, // & this one
    position: { type: String, required: true },
    verficationKey: { type: String, required: true }
});

module.exports = mongoose.model('User', userSchema);

现在,我想在许多用户上更新状态”和“积分”键。但是对于每个用户,他们可能——而且可能会——不同。例如,假设一位用户可能已经有 10 分并且必须获得 +15,而另一位用户可能有 25 分并且必须获得 +5。我想使用他们的“用户名”键在我的数据库中找到我的用户(因为它是独一无二的,我可以通过我的前端轻松访问它)。我根本不知道这是否可能......我对表达和 mongo 有点陌生,所以请耐心等待并解释 - 如果可能的话。


这是我目前找到的(某种)运行我需要的代码。但首先它一团糟,其次,它很糟糕。

    router.put('/update/points', (req, res, next) => {
    User.find().where('username').in(req.body.uid)
        .exec()
        .then(result => {
            var points = req.body.points;

            result.forEach((item) => {
                points.forEach((user) => {
                    if (item.username === user[0]) {
                        item.points = user[1];
                        item.status = user[2]
                        item.position = user[3];
                        item.save()
                            .then()
                            .catch()
                    }
                })
            })

            res.status(200).json({
                message: "Success"
            })
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({
                error: err
            })
        })
})

这是我想出的,但我一点也不满意。在玩了几个小时后,我找到了这个“解决方案”。但显然它很糟糕而且效率低下。

在此之前我做过类似的事情。这个似乎有效,但我讨厌它。

因此,有了这个“解决方案”,我别无选择,只能在我的前端编写低效的代码。

标签: reactjsexpressmongoosebackend

解决方案


有什么理由不能将uid数组和points数组合并成这样的东西吗?这将使处理服务器上的数据变得更加容易。

[ 
    { username: "user1", points: 10, status: 8, position: 21 }, 
    { username: "user2", points: 6, position: 4 },
    { username: "user3", points: 9 },
    ... 
]

然后你可以在服务器上做这样的事情:

router.put('/update/points', async (req, res, next) => {
    try {
        for (let user of req.body.users) {
            let targetUser = await User.findOne({ username: user.username });
            if (targetUser) {
                // Make the changes and save
                targetUser.points = user.hasOwnProperty("points") ? user.points : targetUser.points;
                targetUser.status = user.hasOwnProperty("status") ? user.status : targetUser.status;
                targetUser.position = user.hasOwnProperty("position") ? user.position : targetUser.position;
                await targetUser.save();
            }
        }

        res.status(200).json({
            message: "Success"
        });
    } catch(err) {
        console.log(err);
        res.status(500).json({
            error: err
        });
    }
});

推荐阅读