0

I have a collection called Users.

Here is an example of a doc.

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

I am trying to push the token into the tokens array for all the docs in a DB migration.

This is what I have tried :

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));
}

By doing this I am only getting the 1st document updated the way I want and not the rest. What am I doing wrong here?

Thanks

Ankit
  • 69
  • 1
  • 6

1 Answers1

0

The call to update only modifies the first matched document. You would need to use updateMany or pass the multi option to affect them all.

This code seems to be finding all documents in the User collection via collscan, and then running a separate update in a forEach loop:

            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 } });
            });

If you want to append the token to the array for every user try using:

            return User.updateMany({},{$push: {tokens: token}})
Joe
  • 25,000
  • 3
  • 22
  • 44
  • I tried using the `multi` option set to true, it still updates just the first document. The `token` that is appended to the `tokens` array is different for all documents, so how do you suggest I use `updateMany` . – Ankit Apr 18 '20 at 07:30