Nodejs, update data in mongodb

1

I'm trying to create an api where I receive 2 parameters, the id of the session and the seat that needs to be reserved

[
 {
  "id":1,
  "tanda" : "7:30am"
  , "asientos" : [
            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,
"tanda" : "9:00am",
"asientos" : [
            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
 ]
}

the query to mongo is this

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

but wanting to do it in nodejs

router.put('/reservar/:id/:asiento', function(req, res, next) {

horarios.update({"id": req.params.id}, { "$set":{ "asientos." + req.params.asiento +: "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": "No se pudo reservar el asiento"});
  }
});

I get SyntaxError error: Unexpected token +

    
asked by Alexei Rodriguez 01.08.2017 в 19:43
source

1 answer

0

This error is due to the fact that when defining the name of a property of an object, you can not concatenate strings in the usual way.

If you work with ECMAScript 6, the following is enough:

router.put('/reservar/:id/:asiento', function(req, res, next) {

  horarios.update({"id": req.params.id}, { "$set":{ ["asientos." + req.params.asiento] : "1"}}, function(err, doc) {
    if (err) {
      console.log(err);
      // La línea siguiente también marcaba error porque no asignaste ningún valor a la propiedad error.
      return res.status(400).json({"error" : "Otro error"});
    }
    if (doc.result.nModified) {
      res.status(200).json({"status": "ok"});
    } else {
      res.status(400).json({"error": "No se pudo reservar el asiento"});
    }
  });

}

Otherwise inside your router.put () function, before calling schedules.update (), you must define a variable where you store the string: "entries." + req.params.asiento. And then pass this as property on the set.

    
answered by 02.08.2017 / 17:02
source