Mongo check if value exists, if yes then edit the collection

Hello,

I have a mongo db collection named cars.

Cars = new Mongo.Collection('cars');

Only people who’s IDs are in the element can see those elements.

Meteor.publish('cars', function(){

return Trips.find({userId: this.userId});
});


I have addCar function available, however… How can I check if carNum is already added? If carnum is added then change the values of model\mark\consumption\regDate but add userIds, so that multiple people will be now added to that car.

 Meteor.methods({

addCar: function(carNum, regDate, mark, model, consump){
if(!Meteor.userId()){
	throw new Meteor.Error('No access: You are not logged in.');
}

Cars.insert({
userId: Meteor.userId(),
createdAt: new Date(),
carNum: carNum,
regDate: regDate,
mark: mark,
model: model,
consump: consump


});

},

Example:

  1. I’ve added a car:
Cars.insert({
userId: USER_A,
createdAt: TODAY,
carNum: **CAR_PLATE1**,
regDate: 2011,
mark: TOYOTA,
model: AVENSIS,
consump: 8

then, I did the following command:

Cars.insert({
userId: USER_B,
createdAt: TODAY,
carNum: **CAR_PLATE1**,
regDate: 2011,
mark: TOYOTA,
model: AVENSIS,
consump: 7

Now… I should still have just one element, but two users should see the car, and consumption should be changed from 8 to 7.

You can use an upsert operation (update + insert).

https://docs.mongodb.com/manual/reference/method/db.collection.update/