D
D
deadkEEper12016-04-18 10:46:02
MongoDB
deadkEEper1, 2016-04-18 10:46:02

How to add mongo model property on condition?

There is an array of ids and a mongo collection of users;
You need to check each user if their id is in the ids array. If there is, then add a new property user.tagged = true;
If there is no id in the array, then user.tagged = false;
The code only checks by id, but it doesn't work to add values.

var taggedIds = [....] 
UserModel.find({}, function (err, userModels) {
                    if (err) {
                        return cb(err);
                    }

                    async.each(userModels, function (user) {
                        if (taggedIds.toStringObjectIds().indexOf(user._id.toString()) !== -1) {
                            user.tagged = true;           // как именно добавлять и сохранять новые свойства?
                            console.log('Matched');
                        } else {
                            user.tagged = false;
                            console.log('Not matched');
                        }

                        user.save()
                    });
                    cb(null, userModels);
                });
            }

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel, 2016-04-18
@deadkEEper1

db.usermodel.update({_id: {$in: [... taggedIds ...]}}, {$set: {tagged: true}}, {multi: true}); 
db.usermodel.update({_id: {$nin: [... taggedIds ...]}}, {$set: {tagged: false}}, {multi: true});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question