Mongoose populate cross database not working

Trying to populate postDB collection with user’s information from userDB:

mongoose.connect("mongodb://localhost:27017/userDB")

const postDbConnection = mongoose.createConnection('mongodb://localhost:27017/postDB')

const userSchema = new mongoose.Schema({

email: String,
password: String,
googleId: String,
});

const postSchema = new mongoose.Schema({
title: String,
content: String,
created:
{type: Date, default: Date.now},
user: [{ type: mongoose.Schema.Types.ObjectId, ref: User, required: true }]
});

userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);

// this uses the default connection (to userDB)
const User = new mongoose.model("User", userSchema);

// this uses the second connection (to postDb)
const Post = postDbConnection.model('Post', postSchema);

I get the following error:

Cannot access 'User' before initialization

Unless I use
ref: ‘User’
instead of
ref: User
Which is not the correct way to refer to a model name from an outside connection

16 thoughts on “Mongoose populate cross database not working”

Leave a Comment