0

I am using

db.hs.update( 
     {username: "hraj3116", "event_movie.name": "h"},
     {$set:{"event_movie.$.theatre":"vikas mall"}
     })

this to update in mongodb and this is working fine. How Can I use this using mongoose. I want "event_movie" as variable.

I am using

var  s = {'event_movie.name' : 'h'};
var event = {"event_movie.$.theatre" : "theatre"}; 
//event["event_movie.$.theatre"] = "theatre";
UserEventsDetails.findOneAndUpdate(
{ "username": username , s },
{ "$set": event },
{ "upsert": true, "new": true},
function(err, model){
    if (err){
        res.send(500, err);
    }else{
          res.send('done');
    }
});
Himanshu Raj
  • 113
  • 2
  • 8
  • 3
    I see that you have not accepted any of the answers to your questions. Though it is not an obligation, it helps the community and other users, in general if you accept answers that solve your problem. – BatScream Mar 12 '16 at 03:47
  • Possible duplicate of [Using a variable for a key in a JavaScript object literal](http://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal) – Blakes Seven Mar 12 '16 at 04:37

1 Answers1

1

There is no difference, in the query that we use to update via the shell or using mongoose API. In your case, you need to slightly modify your query parameter:

var query = {};
query["username"] = username;
query["event_movie.name"] = "h";

to produce the correct representation, which is:

{"username":username,"event_movie.name":"h"}

and then use it as:

var event = {};
event["event_movie.$.theatre"] = "theatre";
//event["someOtherField"] = "someOtherValue"; --> update some other field.

UserEventsDetails.findOneAndUpdate(
query,
{ "$set": event },
{ "upsert": true, "new": true},
function(err, model){
    if (err){
        res.send(500, err);
    }else{
          res.send('done');
    }
});

The way you currently build the query, it ends up being constructed as:

{"username":username,{"event_movie.name":"h"}}

which is wrong.

BatScream
  • 19,260
  • 4
  • 52
  • 68