node.jsmongoosemongoose-populate

Referencing a document from another database in mongoose?


How can I reference a document from another database?

This is how I'm connecting to the databases as mentioned in the docs (Docs):

import mongoose from "mongoose";

export default async function connect() {
  const usersConn = await mongoose
    .createConnection(process.env.USERS_MONGO_URI)
    .asPromise(); // Wait for the connection to be created
  const videosConn = await mongoose
    .createConnection(process.env.VIDEOS_MONGO_URI)
    .asPromise(); // Wait for the connection to be created

  const User = usersConn.model(
    "User",
    new mongoose.Schema({
      id: {
        type: String,
        required: true,
      },
      name: {
        type: String,
        required: true,
      },
      email: {
        type: String,
        required: true,
      },
      image: {
        type: String,
        required: true,
      },
    })
  );

  const Video = videosConn.model(
    "Video",
    new mongoose.Schema({
      title: {
        type: String,
        required: true,
      },
      path: {
        type: String,
        required: true,
      },
      author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    })
  );

  return {
    usersClient: usersConn.getClient(), // For next-auth
    User,
    Video,
  };
}

But when I try to populate my query:

const video = await Video.findById(
  new mongoose.Types.ObjectId(id as unknown as string)
)
  .populate("author")
  .exec((err, v) => {
    console.log(err, v);
  });

It gives me the following error:

MissingSchemaError: Schema hasn't been registered for model "User". Use mongoose.model(name, schema)


Solution

  • I've been trying to look for this for a long time, but I'm unable to find an answer. The way I solved this, although a bit hacky, is by saving the id in a field called author_id, then searching through the User model for the id when querying.