TransWikia.com

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

Stack Overflow Asked by Ararat Harutyunyan on December 30, 2021

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

5 Answers

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)

Answered by ChrisMcJava on December 30, 2021

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)

Answered by RickV on December 30, 2021

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

Answered by Ganesh Apune on December 30, 2021

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

Answered by Alex Zaharchuk on December 30, 2021

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

Answered by Furkan Başaran on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP