Mongoose populate cross database not working

Trying to populate postDB collection with user’s information from 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,
{type: Date, default:},
user: [{ type: mongoose.Schema.Types.ObjectId, ref: User, required: true }]


// 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