Does not work when foreignField uses autopopulate
BGOnline-CN opened this issue · 1 comments
BGOnline-CN commented
Reproduce
// company
const companySchema = mongoose.Schema({
users: [{ type: ObjectId, ref: 'User', autopopulate: true }]
});
companySchema.virtual('job', {
ref: 'Job',
localField: 'users',
foreignField: 'user',
autopopulate: true
});
const Company = mongoose.model('Company', companySchema);
// job
const jobSchema = mongoose.Schema({
user: { type: ObjectId, ref: 'User', autopopulate: true }
});
const Job = mongoose.model('Job', jobSchema);
// company find
const res = await Company.find().lean({ autopopulate: true });
The above code res
will output:
{
users: [ {xxx}, {xxx}, {xxx} ],
job: []
}
When i remove jobSchema.user.autopopulate
const jobSchema = mongoose.Schema({
user: { type: ObjectId, ref: 'User' }
});
Everything works fine at this point
So I want to know, How to keep autopopulate of jobSchema
vkarpov15 commented
It doesn't look like you're actually registering the mongoose-autopopulate plugin. You need to actually register the plugin on your schema, see the mongoose plugin docs. Below script works:
'use strict';
const mongoose = require('mongoose');
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();
// company
const companySchema = mongoose.Schema({
users: [{ type: mongoose.ObjectId, ref: 'User', autopopulate: true }]
});
companySchema.virtual('job', {
ref: 'Job',
localField: 'users',
foreignField: 'user',
justOne: true,
autopopulate: true
});
companySchema.plugin(require('mongoose-autopopulate'));
const Company = mongoose.model('Company', companySchema);
// job
const jobSchema = mongoose.Schema({
user: { type: mongoose.ObjectId, ref: 'User', autopopulate: true }
});
const Job = mongoose.model('Job', jobSchema);
const User = mongoose.model('User', mongoose.Schema({ name: String }));
const id = new mongoose.Types.ObjectId();
await Company.create({ users: [id] });
await Job.create({ user: id });
// company find
const res = await Company.find().lean({ autopopulate: true });
console.log(res[0], res[0].job);
}