Jose
Jose

Reputation: 1239

NodeJS / Mongoose Filter JSON

I am building a JSON API with ExpressJS, NodeJS and Mongoose:

Input -> id:

app.get('/folder/:id', function (req, res){
  return Cars.find({reference: req.params.id}, function (err, product) {
    if (!err) {
      console.log(product);
      return res.send(product);
    } else {
      return console.log(err);
    }
  });
});

It shows well the JSON:

[{"_id":"B443U433","date":"2014-08-12","reference":"azerty","file":"087601.png","
....:.
{"_id":"HGF6789","date":"2013-09-11","reference":"azerty","file":"5678.pnf","
...

I just want to display the _id in the JSON, so it is good when I have lots of data.

How I can do that? Something like a filter?

Upvotes: 0

Views: 1718

Answers (3)

Elyas74
Elyas74

Reputation: 548

Other answers are true but I think it's better to limit data in mongoose like this :(it's same as mongo shell commands)

app.get('/folder/:id', function (req, res){
    Cars.find({reference: req.params.id} ,{ _id : true } ,function (err, product) {
        if (!err) {
            console.log(product);
        } else {
            console.log(err);
        }
    });
});

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 312035

You can chain calls to select and lean to retrieve just the fields you want from the docs you're querying:

app.get('/folder/:id', function (req, res){
  return Cars.find({reference: req.params.id}).select('_id').lean().exec(
    function (err, product) {
      if (!err) {
        console.log(product);
        return res.send(product);
      } else {
        return console.log(err);
      }
    });
});

Upvotes: 2

tier1
tier1

Reputation: 6433

You would have to iterate over your "products" object to obtain the ids

Something like this: (Disclaimer: I haven't tested this)

  app.get('/folder/:id', function (req, res){
  return Cars.find({reference: req.params.id}, function (err, product) {
    if (!err) {
      console.log(product);

      var ids = new Array();
      for(var i = 0; i < product.length; i++){
          ids.push(product[i]._id);
      }
      return res.send(JSON.stringify(ids));
    } else {
      return console.log(err);
    }
  });
});

--Edit

Also, "products" may already be a JSON string. You may want to parse it before looping.

product = JSON.parse(product);

Upvotes: 0

Related Questions