Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove mongo specific fields from result (NodeJS, Mongoose)

I want to remove all Mongo specific fields (like '_id') from query result. Is there a simple method to do this or should I remove fields manually? If yes, then which are that fields and how to do that?

I'm using NodeJS and Mongoose

like image 634
Ararat Harutyunyan Avatar asked Nov 19 '15 09:11

Ararat Harutyunyan


3 Answers

You can use select() method for remove the field from your query:

Model.find({}).select("-removed_field").then (resp => {
// your code        
});

You should specified the "-" before field name, to be remove this field. If you want remove several fields - you can specified their as array:

Model.find({}).select(["-removed_field1", "-removed_field2" ... ]).then (resp => {
// your code        
});

Also you can to select only specified fields, using this method without "-"

Model.find({}).select(["field1", "field2" ... ]).then (resp => {
// your code        
});
like image 61
Alex Zaharchuk Avatar answered Oct 13 '22 19:10

Alex Zaharchuk


If you want hide _id property you can use text argument with prefix - which will exclude this or that field from the result, for get sepecifict fields you should pass like this:

Entity.find({ ... }, 'field1 field2', function(err, entity) {
    console.log(entity);  // { field1: '...', field2: '...' }
});
like image 39
Furkan Başaran Avatar answered Oct 13 '22 21:10

Furkan Başaran


You can specify a field to be excluded from results by using the optional 2nd parameter projection string of the find method:

Model.find({}, "-a -b").then (res => {
    // objects in the res array will all have the 
    // 'a' and 'b' fields excluded. 
});

https://mongoosejs.com/docs/api.html#model_Model.find (see projection)

like image 29
ChrisMcJava Avatar answered Oct 13 '22 20:10

ChrisMcJava