【问题标题】:Appending an array field, from another field, in MongoDB documents (with MongoClient) in Node.js在 Node.js 的 MongoDB 文档(使用 MongoClient)中从另一个字段附加一个数组字段
【发布时间】:2020-07-31 10:22:50
【问题描述】:

我有一个名为“用户”的集合。

这是一个文档的示例。

{"_id":{"$oid":"xxxxxxxxxxxxxxxxxxx"},
"userId":"ANKIT",
"token":"token123",
"badge":{"$numberInt":"0"},
"useLocalCurrency":true,
"notifyCustomerRejected":true,
"notifyReworkRequest":true,
"notifyMoaApproved":true,
"notifyCustomerAccepted":true,
"__v":{"$numberInt":"0"},
"tokens":[]}

我正在尝试将 token 推送到数据库迁移中的所有文档的 tokens 数组中。

这是我尝试过的:

export function up(next) {
    let mClient = null;
    return MongoClient.connect(url)
        .then(client => {
            mClient = client;
            return client.db('notifications');
        })
        .then(db => {
            const User = db.collection('users');
            return User.find().forEach(result => {
                let { _id, userId, tokens, token } = result;
                tokens.push(token);
                tokens = Array.from(new Set(tokens));
                result.tokens = tokens;
                console.log(result._id);
                console.log(result.tokens);
                User.update({ _id: _id, userId: userId }, { $set: { tokens: tokens } });
            });
        })
        .then(() => {
            mClient.close();
            return next();
        })
        .catch(err => next(err));
}

通过这样做,我只会按照我想要的方式更新第一个文档,而不是其余的。我在这里做错了什么?

谢谢

【问题讨论】:

    标签: javascript node.js mongodb dbmigrate


    【解决方案1】:

    update 的调用仅修改第一个匹配的文档。您需要使用updateMany 或传递multi 选项来影响它们。

    这段代码似乎是通过 collscan 查找 User 集合中的所有文档,然后在 forEach 循环中运行单独的更新:

                return User.find().forEach(result => {
                    let { _id, userId, tokens, token } = result;
                    tokens.push(token);
                    tokens = Array.from(new Set(tokens));
                    result.tokens = tokens;
                    console.log(result._id);
                    console.log(result.tokens);
                    User.update({ _id: _id, userId: userId }, { $set: { tokens: tokens } });
                });
    

    如果您想为每个用户将令牌附加到数组中,请尝试使用:

                return User.updateMany({},{$push: {tokens: token}})
    

    【讨论】:

    • 我尝试使用设置为 true 的 multi 选项,它仍然只更新第一个文档。附加到tokens 数组的token 对于所有文档都是不同的,所以你建议我如何使用updateMany
    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 2014-07-20
    • 2023-02-11
    • 2021-11-13
    • 2013-08-26
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多