2

I have a record like this

{
    "_id" : ObjectId("57025c35e31f7274c1195c26"),
    "token" : "0ffed58b-57ed-4a2a-bb09-97c64f0f2bd2",
    "key" : "silly key",
    "user" : ObjectId("55e3f8fcc78dc516096dc3e2"),
    "twlprofile" : "Test Blog"
}

It is the only one in the collection. I am trying to update and need the update to upsert if it can't find anything, so I have this code

var id = "55e3f8fcc78dc516096dc3e2";
var tokendoc =  {
     "token": "05c50aa0-5a8c-4fad-b27f-db64a0355b4f",
     "key": "silly key",
     "user": "55e3f8fcc78dc516096dc3e2",
     "twlprofile": "Test Blog"
}
var tokenrecord = tokensCollection.update(
                     { where: { user: id } },
                     tokendoc,
                     { upsert: true },
                     function(err,tokenres){
                       //this part not important right now
                     });

which if I run it ends up inserting another document with the same user property. I have also tried using BSON.ObjectID with the id variable and it doesn't help.

How do I get this to work like a real upsert?

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
user254694
  • 1,461
  • 2
  • 23
  • 46
  • use updateOne instead of update then it will work – Suresh Mahawar Apr 04 '16 at 13:01
  • http://stackoverflow.com/questions/7267102/how-do-i-update-upsert-a-document-in-mongoose – SiddAjmera Apr 04 '16 at 13:02
  • `{ where: { user: id } }` should be `{ user: id }`. – JohnnyHK Apr 04 '16 at 13:10
  • neither updateOne or findOneAndUpdate work to insert anyting if there isn't a document there, even with upsert: true. – user254694 Apr 05 '16 at 08:10
  • change from where user id query to just user: id worked. Why is that? There are parts where nothing works unless I use where and parts where it doesn't work. reading the documentation on where doesn't seem to clarify why that is. – user254694 Apr 05 '16 at 08:12
  • @user254694 You never need the `where:` in a query object. Are you maybe confusing that with the [`$where`](https://docs.mongodb.org/manual/reference/operator/query/where/#where) operator? – JohnnyHK Apr 06 '16 at 12:45

0 Answers0