Nisha
Nisha

Reputation: 158

How to update a document in mongo db by matching user Id if it exists and insert if does not exist using upsert in meteor?

I want to update a document when it matches user Id entered in Url and if it does not exist then insert it.Here in my code update is working fine but insert has some issue as i am matching _id with given to update .so is there any other way to match user Id in document with given user Id ? Anyone help me with this issue. Below is my code:

     var p = Dbs.findOne({ user_id: Router.current().params._id });
     Dbs.update({ _id: p._id }, {
       $set: {
        user_id: user_id1,
        cont: cont1,
        add: add1,
        pth: pth1
      }
    },
    {upsert:true}
    );

I tried using {User_id:p._id} in place of { _id: p._id } but its not working.

Upvotes: 0

Views: 1729

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20256

If I understand your question correctly you just want to match on user_id instead of _id. Then just use that in your selector:

Dbs.update({ user_id: your_user_id_value },
  {
    $set: {
      user_id: user_id1,
      cont: cont1,
      add: add1,
      pth: pth1
    }
  },
  { upsert: true}
);

This will work if there's only one document found. If the match finds multiple documents then only the first one will be modified unless you also specify multi: true in your options. Note also that this code will only work on the server.

Upvotes: 1

Related Questions