Ararat Harutyunyan
Ararat Harutyunyan

Reputation: 926

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

Upvotes: 11

Views: 20036

Answers (6)

Saif Uddin
Saif Uddin

Reputation: 187

if You want to remove any specific fields like _id, You can try in two ways: Suppose Here you try to find a user using User Model

User.find({ email: email }, { _id: 0 });

OR

const user = User.find({ email: email });
delete user._doc._id;

Upvotes: 1

ChrisMcJava
ChrisMcJava

Reputation: 2293

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)

Upvotes: 4

Anubhab Maji
Anubhab Maji

Reputation: 648

OP mentioned "from result", as far as I understood, it means, removing from the query result i.e. query result will contain the field, but will be removed from the query result.

A SO answer here mentions, that to modify a query result (which are immutable), we've to convert the result to Object using toObject() method (making it mutable).

To remove a field from a query result,

let immutableQueryResult = await Col.findById(idToBeSearched)
let mutableQueryResult = immutableQueryResult.toObject()
delete mutableQueryResult.fieldToBeRemoved
console.log(mutableQueryResult)

Another way of getting the mutable result is using the _doc property of the result:

let immutableQueryResult = await Col.findById(idToBeSearched)
let mutableQueryResult = immutableQueryResult._doc    // _doc property holds the mutable object
delete mutableQueryResult.fieldToBeRemoved
console.log(mutableQueryResult)

Upvotes: 1

Ganesh Apune
Ganesh Apune

Reputation: 197

you can use mongoose instance method two show specific fields from all documents

const userSchema = new mongoose.Schema({
email: {
type: String,
},

name: {
type: String,
maxlength: 128,
index: true,
trim: true,
},
});
userSchema.method({
   transform() {
   const transformed = {};
   const fields = ['name', 'email'];

      fields.forEach((field) => {
      transformed[field] = this[field];
      });
   return transformed;
   },
});
module.exports = mongoose.model('User', userSchema);

Upvotes: 1

Alex Zaharchuk
Alex Zaharchuk

Reputation: 345

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        
});

Upvotes: 23

Furkan Başaran
Furkan Başaran

Reputation: 1947

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: '...' }
});

Upvotes: 5

Related Questions