I have the follwing schemas :
const Entity = new Schema(
{
name: {
type: String,
required: true,
},
accounts: [account.schema],
},
const Account = new Schema(
{
name: {
type: String,
required: true,
},
phone, address ,....
},
and invoice :
const Invoice = new Schema(
{
number: {
type: Number,
index: true,
default: 0,
},
customer: {
type: Schema.Types.ObjectId,
ref: "Entity",
},
account: {
type: Schema.Types.ObjectId,
ref: "Account",
},
is the any way that I can populate the account field in the invoice query ?
await invoiceModel
.find({})
.sort({ _id: -1 })
.populate("customer")
.populate("account")
.then((invoices) => {
console.log(invoices);
resolve(invoices);
})
or I have design mistake? any help will be much appreciated
Your schema design looks fine but you are incorrectly chaining then
blocks to the await
return value. Try this:
const invoices = await invoiceModel.find({})
.populate({ path: 'customer', model: CustomerModel })
.populate({ path: 'account', model: AccountModel})
.sort({ _id: -1 });
I have included model: ModelName
for each populate in the event you need to register the model as it may not be in scope depending on your design.