0

In a Meteor Mongo Collection, is it possible that we check if a field exists and if not not, add that field ?

Syed Is Saqlain
  • 360
  • 1
  • 3
  • 13
  • Possible duplicate of [Meteor upsert equivalent](http://stackoverflow.com/questions/13206015/meteor-upsert-equivalent) – Mario Trucco May 02 '16 at 12:38

1 Answers1

2

Yes. You need to use the $exists operator in your Mongo query. For example with a collection called Posts:

Posts.update({
    _id: 'abcdef123',
    myField: {
        $exists: false
    }
}, {
    $set: {
        myField: 'myValue...'
    }
});

If myField already exists, that field will not be updated.

The caveat here would be that if you want to update other fields regardless of myField existing or not, you'd need to do that in a separate update query.

Michael Mason
  • 932
  • 5
  • 15