0

This is my code:

router.post('/findmanychallengesbyid', auth, function(req, res, next){
  if(!req.body.ids){
    return res.status(400).json({message: 'Geen ids'});
  }

  var challengeData = [];
  for( var i = 0; i < JSON.parse(req.body.ids).length; i++ ) {
    Challenge.findById(JSON.parse(req.body.ids)[i].toString().replace(/\"/g, ""), function (err, doc){
      challengeData.push(doc);
    });
  }

  res.json(challengeData);

});

Challenge is a schema from my nodejs app.

When I do res.json(JSON.parse(req.body.ids)) I get:

[
  "56313da58c5ba50300f2b4f0",
  "564cac9c097c07030038cac0",
  "563140668c5ba50300f2b4f3"
]

Challenge.findById requires this as input:

56313da58c5ba50300f2b4f0

Now it gets this as input:

"56313da58c5ba50300f2b4f0"

So how can I accomplish this?

  • 1
    This question looks like you're trying to solve a small problem that's part of a bigger problem, and there may be a different simpler way of solving the bigger problem. What is your larger goal with this? – Jon Surrell Nov 25 '15 at 12:02
  • 1
    Regarding *this* problem, is `"563140668c5ba50300f2b4f3"` a console representation, or are `"` actually in the string? – Jon Surrell Nov 25 '15 at 12:03
  • unquoted `563140668c5ba50300f2b4f3` is not a valid represenation of anything in JavaScript. It would have to be treated as a string. – Jon Surrell Nov 25 '15 at 12:04
  • I have edited the op for more detailed info. –  Nov 25 '15 at 12:13
  • What does `req` look like? It's a javascript object that includes some unparsed string? Where does `Challenge` come from? – Jon Surrell Nov 25 '15 at 12:16
  • req is just from nodejs, the code is part of a API route in nodejs. Challenge is a schema. –  Nov 25 '15 at 12:21
  • There is no such JS syntax as `56313da58c5ba50300f2b4f0`. –  Nov 25 '15 at 12:24

3 Answers3

1

use this :

.replace(/\"/g, "")

to replace the ""

Hasan Daghash
  • 1,681
  • 1
  • 17
  • 29
1

You want to search for an array of id's if I understand the code correctly.

The proper way to do is, is to use .find

router.post('/findmanychallengesbyid', auth, function(req, res, next){
  if(!req.body.ids){
    return res.status(400).json({message: 'Geen ids'});
  }

  Challenge.find({
    '_id': { $in: JSON.parse(req.body.ids)}
    }, function(err, docs){
      res.json(docs);
  });

});
stijn.aerts
  • 6,026
  • 5
  • 30
  • 46
0

Convert the JSONValue to to String:

String.ValueOf(iets);

or you may use the replaceAll function of String Class

iets.toString().replaceAll("\"", "");

This method replace all the double quotes which are present in your iets not the first and the last.

Example : "Hello" becomes Hello but if its as "He"llo" it should be He"llo according to your requirement but it becomes Hello. Mean to say that all the double quote replaced.

Zia
  • 1,001
  • 1
  • 13
  • 25