0

Here is my Schema:

    var User = new Schema({
        name: {type: String, required: true},
        email: {
            address: String,
            confirmed: Boolean,
            confirm_code: String
        },
        saved_artists: [Schema.ObjectId],
        new_releases: [Schema.ObjectId],
        sync_queue: {
            id: Number,
            status: String
        }
    });

and

var Artist = new Schema({
    spotify_id: {type: String, required: true},
    name: {type: String, required: true},
    recent_release: {type: {
        id: String,
        title: String,
        release_date: String,
        images: []
    }, required: true},
    users_tracking: [Schema.ObjectId]
});

and here is my update query:

User.update({_id: {$in: artist.users_tracking}}, {$addToSet: {'new_releases': artist._id}}, function (err) {
        if (err) {
            // todo turn into debug report
            console.log(err);
        }
        User.find({}, function (err, users) {
            console.log(users);
        })
    })

When I run a unit test, $in only selects the first _id of the array and updates that one and ignores any others. The input array looks like this:

["5993864f44456a1b50378bc3","5993864f44456a1b50378bc4"]

and if I run the update query iteratively like below, it outputs correctly:

for (var i =0; i < artist.users_tracking.length; i++){
        User.update({'_id': artist.users_tracking[i]}, {$addToSet: {'new_releases': artist._id}}, function(err) {

        })
    }
Ryan
  • 323
  • 2
  • 12

2 Answers2

0

Changing User.update() to User.updateMany() provided the expected query output.

Ryan
  • 323
  • 2
  • 12
0

You can also set the multi option to true.

User.update({
    _id: { $in: artist.users_tracking }
}, { 
    $addToSet: { new_releases: artist._id }
}, { 
    multi: true 
}, ...)
Mikey
  • 6,728
  • 4
  • 22
  • 45