mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
221 stars 36 forks source link

Can't set default maxDepth for fields #72

Closed jmikrut closed 4 years ago

jmikrut commented 4 years ago

Hi there, sorry in advance if I am missing something but it seems like I am unable to set a default maxDepth property on a field.

For example, if I create a field like this:

  friends: [{
    type: Schema.Types.ObjectId,
    ref: 'User',
    autopopulate: { maxDepth: 2 }
  }]

maxDepth is not taken into account properly. From the docs, it seems like this should be supported.

Is this a problem with my configuration?

vkarpov15 commented 4 years ago

The below script works as expected. Can you please modify the below script to demonstrate your issue?

'use strict';

const mongoose = require('mongoose');
const autopopulate = require('mongoose-autopopulate');

mongoose.set('useFindAndModify', false);

const { Schema } = mongoose;

run().catch(err => console.log(err));

async function run() {
  await mongoose.connect('mongodb://localhost:27017/test', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });

  await mongoose.connection.dropDatabase();

  const schema = Schema({
    friends: [{
      type: Schema.Types.ObjectId,
      ref: 'User',
      autopopulate: { maxDepth: 2 }
    }]
  });
  schema.plugin(autopopulate);
  const User = mongoose.model('User', schema);

  const test = await User.create({ friends: [] });

  test.friends.push(test);
  await test.save();

  const doc = await User.findById(test);
  console.log(require('util').inspect(doc, { depth: 10, colors: true }));
}