How to ensure only one value is true in DB in Meteor App


I want to activate only one document at one time by click of button. For this I am using a flag: “active”.

‘click .active’: function (){
var status = nodeDB.findOne({active:true});
nodeDB.update( {$set:{‘active’:1}});
//How to set the other documents as inactive

Elements in MongoDB

Document1: {Keys->value,active->1}
Document2: {Keys ->value,active->0}


This is potentially a very expensive operation. Instead, consider using the current active document’s _id.


If you’re using user accounts, take robfallows’ suggestion and save the active doc id to a field on the user doc. If user accounts don’t really apply, maybe a separate collection where you can save state data.


I agree with others that it isn’t a good solution. Anyway you can try next:

firstActiveId = nodeDB.findOne({active: true})._id;
nodeDB.update({}, {$set: {active: 0}}, function(err, res) {
    if (!err) {
        nodeDB.update(firstActiveId, {$set: {active: 1}});