12

In the code below the query gives me all the fields. I only want to query _id and serialno. How to go about it.

Schema

var DataSchema = new Schema({
  serialno: String,
  info: String,
  active: Boolean,
  content: String
});

Query

// Get list of datas
exports.index = function(req, res) {
  Data.find(function (err, data) {
    if(err) { return handleError(res, err); }
    return res.json(200, data);
  });
};
1
  • dataModel.find({ _id : 123456 }, { serialno : 1 }) Commented May 13, 2021 at 17:10

5 Answers 5

32

If you are using latest nodejs mongodb driver 3.0 or above try this code:

Data.find({}).project({ _id : 1, serialno : 1 }).toArray()
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much. None of the other answers work properly.
Yup! This is it! This is the one!
.findOne(...).project is not a function. Bad answer.
@Yeats they are doing a find not a findOne
9

To query and return only specific fields, this is the correct request :

Data.find({}, { _id : 1, serialno : 1 }, function (err, data) {
  if(err) { return handleError(res, err); }
  return res.json(200, data);
});

The second object params is the projection params, in this object, you can set fields to return or hide.

More informations here : http://docs.mongodb.org/manual/reference/method/db.collection.find/

2 Comments

solves my problem. Will mark is as the correct answer.
This will return all fields. Bad answer.
3

In MongoDB Node.js Driver v3.1 and above:

Collection.find({}, {
   projection: {
     _id: false,
     someField: true
   }
});

Second argument to the find/findOne function is options. It supports limit, sort, projection, and many more filters.

Source: http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOne

1 Comment

Haha mongodb is really all over the place with their stupid changes. This is not even in their official documentation. And it doesn't make sense. Projection? Really?
1

Following the documentation, you are using the function collection.find(query[[[, fields], options], callback]);

So you need to specify the fields argument:

Data.find(null, { "_id": true, "serialno": true }, function (err, data) {
    if(err) { return handleError(res, err); }
    return res.json(200, data);
  });

Comments

1

You can use Below code

enter code here`collection.find({}, { projection: {_id:1, serialno: 1}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.