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

2 thoughts on “Mongoose populate cross database not working”

  1. you use User Model in postSchema for population but it’s defined after postschema so just try

    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,
    });
    
    // this uses the default connection (to userDB)
    const User = new mongoose.model("User", userSchema);
    
    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 second connection (to postDb)
    const Post = postDbConnection.model('Post', postSchema);
    
    Reply

Leave a Comment