api-query-params icon indicating copy to clipboard operation
api-query-params copied to clipboard

How to prevent nested populating?

Open samislam opened this issue 3 years ago • 0 comments

I have the following Model:

const userSchema = new mongoose.Schema({
   name: String,
   by: { type: mongoose.Schema.ObjectId, ref: 'User' }
})
const UserModel = mongoose.model('User', userSchema, 'users')

and I am using api-query-params in one of my controllers:

const aqp = require('api-query-params')
app.get('/users', (req, res, next) => {
   const docs = await UserModel.find(aqp.filter).populate(aqp.population)
   res.status(200).json({  data: docs })
})

Let's say there's a user called A who created himself somehow. I am requesting: http://localhost:4000/users?populate=by and I am getting the response as follows:

{ # 200 OK
   data: [
      {
          name: A,
          by: {
              name: A,
              by: 62e7960ebc9aa651523bf5b2 // Object Id
          }
      }
   ]
}

I am OK with this response, however, the problem comes when someone requests http://localhost:4000/users?populate=by.by.by.by

the response becomes:

{
    # 200 OK
    data: [{
        name: A,
        by: {
            name: A,
            by: {
                name: A,
                by: {
                    name: A,
                    by: 62e7960ebc9aa651523bf5b2 // Object ID
                }
            }
        }
    }]
}

Is there an option where I can only allow one level of populating in aqp (api-query-params)?

samislam avatar Aug 01 '22 11:08 samislam