Mongoose populate on ObjectId populate not working

Viewed 16

My schemas:

const AccountSchema = new mongoose.Schema({
  address: {
    type: String,
    required: true,
    index: {
      unique: true,
    },
  })

module.exports = mongoose.model('Account', AccountSchema)
const OrderSchema = new mongoose.Schema({
  description: { type: String },
  account: {
    type: Schema.Types.ObjectId,
    ref: 'Account',
  },

Queries:

const order = await Order.findOne({ _id: orderId }).populate('account');
const order = await Order.findOne({ _id: orderId })
      .populate({path:'account', model:'Account'});
console.log(order.account) //undefined
order.populated('account') // Typedef error, populated not a method

What am I doing wrong?

1 Answers

My mistake, I was not awaiting the promise returned by my query function

BAD

const order = orderQueries.getOrderById(orderId)
console.log(order.account) //undefined
order.populated('account') // Typedef error, populated not a method

GOOD

const order = await orderQueries.getOrderById(orderId)
console.log(order.account) //the account object
order.populated('account') // true
Related