mongoose convert all leaned ObjectIds to String format

Viewed 337

I'm using mongoose-paginate-v2 to paginate my documents, and I use lean=true to make them a plain Object (I want to filter them using accesscontrol.

When I get the leaned Objects , all ObjectIds are in Object formate like below:

{"_id":{"_bsontype":"ObjectID","id":{"type":"Buffer","data":[95,94,16,4,98,8,156,8,236,35,179,155]}}

I get that its the way that MongoDB handles it but I want to send String ObjectId to the client (so that it can access resources with that Id). I know that by using vituals and id instead of _id I can get the string representation of that object's _id, but the problem is I want All ids to be string, not just the id of the object.

If I try to write a middleware that changes all id objects to string representation, I'll need a way to deep find all ids in my result , which I don't know how to do.

How an I have all ids in string format, yet still have leaned object?

1 Answers

May be a little late in replying, we can use lodash transform for this-

var transform = require('lodash.transform');
var isObject = require('lodash.isobject');
const ObjectId = require('mongoose').Types.ObjectId;

const transformObjectId = obj => transform(obj, (acc, value, key, target) => {
    if(value instanceof ObjectId){
        acc[key] = value ? value.toString() : '';
    } else if(value instanceof Date){
        acc[key] = value;
    }else{
        acc[key] = isObject(value) ? transformObjectId(value) : value;
    }
  })

module.exports = {
    transformObjectId: transformObjectId
}

Related