0

I'm trying to make an api for a bus ticketing sistem, but I can't seem to get an how to make it work in nodejs

[
 {
  "id":1,
  "hour" : "7:30am"
  , "seats" : [
            0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0 ,0, 0
 ]
},
{
"id":2,
"hour" : "9:00am",
"seats" : [
            0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0, 0 ,
   0, 0, 0 ,0, 0
 ]
}

This is my mongodb query

db.schedules.update({"id":2}, {"$set" : {"seats.8" : "1"}});

and everything seems to work just fine until I try it on nodejs

router.put('/reserve/:id/:seat', function(req, res, next) {
  schedules.update({"id": req.params.id}, { "$set":{ "seats." + req.params.seat+: "1"}}, function(err, doc) {
    if (err) {
      console.log(err);
      return res.status(400).json({"error"});
    }
    if (doc.result.nModified) {
      res.status(200).json({"status": "ok"});
    } else {
      res.status(400).json({"error": "The seat hasn't been reserved"});
    }
  });

this is the error returned:

SyntaxError: Unexpected token +

I have tried multiple ways and can't get that working

alexmac
  • 19,087
  • 7
  • 58
  • 69

1 Answers1

1

You have invalid javascript syntax here: schedules.update({"id": req.params.id}, { "$set":{ "seats." + req.params.seat+: "1"}} Can't concat a string in an object definition.

Try like this, using a property reference notation (that will create the property):

let updateObj = { $set: {} }
updateObject.$set['seats.' + req.params.seat] = '1'
schedules.update({"id": req.params.id}, updateObj, function ... )
clay
  • 5,917
  • 2
  • 23
  • 21