1

I am running a special query in which I want transform the results after.

User.find({}, function(err, users) {
  // I want to remove/add some properties from/to each user here
});

Is there a way to transform an array of documents? Also this is a special case so I do not want to apply a transformation to the Schema, which I think would transform each document like I want, but would also affect all other queries to the User model.

Basically I want the ability to perform a one time transformation on the array of docs returned.

User.find({}, function(err, users) {
  // I want to remove/add some properties to each user here
  users.toJSON({transform: function(doc,ret,options) { /* do tranform*/ });
  // That will not work as I get an error that toJSON is not defined for that
  // array that was returned.
});

I might be able to fake it out by adding a transformation right before I query and then removing that transformation when the query is complete, but that is a pretty bad hack IMHO.

Ideas? Did I miss something in the docs?

1 Answer 1

7

You can use a lean query so that an array of plain JS objects are returned from the query and then use map to transform the array:

User.find({}).lean().exec(err, users) {
    users = users.map(function(user) {
        // transform user into newuser as needed.
        ...
        return newuser;
    });
});
Sign up to request clarification or add additional context in comments.

5 Comments

Works great, thanks. Hoping there was a way to transform each object before I get the array back. In the end its the same loop regardless just on my end instead of mongoose.
Note: lean has consequences other than turning a query into plain JS objects, such as getting rid of virtuals, methods, etc. What I needed was just to use the toObject() method on the items in the query (using map) instead.
@Nate can you please help me in understanding how to use toObject() on an array of documents.
@rakeshkashyap: var usersObj = users.map(function (user) { return user.toObject(); });
@rakeshkashyap Or, these days: let usersObj = users.map(user => user.toObject());

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.