Reputation: 155
User schema looks something like this
addressId: [{ type: mongoose.Schema.Types.ObjectId, ref: 'address' }],
mongoose.model('user', userSchema);
Address model
mongoose.model('address', postalAddressSchema);
I am trying to do this:
const createdUser = await mongoose.models.user.create(user);
return { success: true, user: createdUser.populate('addressId') };
I am trying to populate address in user creation. It returns null
Upvotes: 1
Views: 41
Reputation: 1024
You may try to find, populate and exec after creating the user. Here is a working example
const theMongoose = await mongoose.connect(mongoServerUri);
const accountModel = theMongoose.model(
'Account',
new Schema({
_id: Schema.Types.ObjectId,
name: String
})
);
const activityModel = theMongoose.model(
'Activity',
new Schema({
account: { type: Schema.Types.ObjectId, ref: 'Account' },
date: Date,
desc: String
})
);
const account = await accountModel.create({ name: "Test User", _id: mongoose.Types.ObjectId.createFromTime(new Date().getTime()/1000) });
await activityModel.create({ date: new Date(), desc: "test", account: account.id });
// find, populate, & exec
const res = await activityModel.find({ desc: "test" }).populate("account").exec()
console.log(res);
And the output is
[
{
_id: new ObjectId("62da50ec77c026e2aad5577b"),
account: {
_id: new ObjectId("62da50ea0000000000000000"),
name: 'Test User',
__v: 0
},
date: 2022-07-22T07:25:32.119Z,
desc: 'test',
__v: 0
}
]
Upvotes: 1