mongodb-js / mongoose-autopopulate

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

Mongoose does not support calling populate() on nested docs #71

Closed eliasjnior closed 4 years ago

eliasjnior commented 4 years ago

I got this error trying to:

const order = await OrderModel.findById(orderId)
order.set(data)
await order.save()

Here's my schema for Order:

{
    user: {
      type: Types.ObjectId,
      required: true,
      ref: 'User',
      autopopulate: true,
    },
    status: {
      type: String,
      required: true,
    },
    address: orderAddressSchema,
    products: [orderProductSchema],
    subtotal: {
      type: Number,
      required: true,
    },
    shipping: {
      type: Number,
      required: true,
    },
    total: {
      type: Number,
      required: true,
    },
  }

And here for order address:

{
  street: {
    type: String,
    required: true,
  },
  number: {
    type: String,
    required: true,
  },
  neighborhood: {
    type: String,
    required: true,
  },
  complement: {
    type: String,
    default: '',
  },
  city: {
    type: String,
    required: true,
  },
  state: {
    type: String,
    required: true,
  },
  country: {
    type: String,
    required: true,
  },
  postcode: {
    type: String,
    required: true,
  },
}

And finally for order products:

{
  product: {
    type: Types.ObjectId,
    ref: 'Product',
    required: true,
    autopopulate: true,
  },
  title: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  quantity: {
    type: Number,
    required: true,
  },
  total: {
    type: Number,
    required: true,
  },
}

The message recommends use doc.populate("arr.0.path") than doc.arr[0].populate("path"). I'm using version 0.12.1 from NPM.

eliasjnior commented 4 years ago

By the way, the workaround was don't set and update, but using:

await OrderModel.findByIdAndUpdate(orderId, data)
eliasjnior commented 4 years ago

For what I searched, the problem is here: https://github.com/mongodb-js/mongoose-autopopulate/blob/master/index.js#L57

But I still didn't figure out how to fix.

eliasjnior commented 4 years ago

Looks like I was adding auto populate plugin in each subdocument schema, this was causing the problem. If I remove the plugin from subdocuments, the fields that I set as autopopulate still working, so no need to apply plugin on subdocuments.

vkarpov15 commented 4 years ago

Fixed in https://github.com/mongodb-js/mongoose-autopopulate/commit/338e7737ae1b643287e82cd883f7818015af65be .

vkarpov15 commented 4 years ago

Now registering this plugin on a nested schema is a no-op rather than throwing an error on post('save')