Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose populate schema from different Database

For example i have SchemaA and SchemaB which both belong to different database. Inside SchemaA i have doc.b = {type: mongoose.Schema.Types.ObjectId, ref: 'SchemaB'}. When i am doing populate of this i got below error. MissingSchemaError: Schema hasn't been registered for model "SchemaB". Use mongoose.model(name, schema) From my research i have read that mongoose support population cross databases.
I am requiring mongoose multiple times for each schema, is that the problem?
Basically what i need is two different schema which is connecting to different databases to work together with populate. If i register schema on connection created by mongoose they will not be registered on the same list. If there a way to success that?

like image 708
Honchar Denys Avatar asked May 01 '16 02:05

Honchar Denys


2 Answers

Basically what we need to do is pass schema to population, something like this:

User.findOne({
    _id: req.user._id
}).populate({
    path: 'roomsContainer',
    model: RoomsContainer,
    populate: [{
        path: 'creator'
    },{
        path: 'users'
    },{
        path: 'rooms',
        model: Room
    }]
}).exec(function(err, user) {
    // do some magic
});

Where User belong to database one and Room, RoomsContainer belong to database two.

like image 102
Honchar Denys Avatar answered Oct 14 '22 14:10

Honchar Denys


const db1 = mongoose.createConnection('mongodb://localhost:27000/db1');
const db2 = mongoose.createConnection('mongodb://localhost:27001/db2');

const conversationSchema = new Schema({ numMessages: Number });
const Conversation = db2.model('Conversation', conversationSchema);

const eventSchema = new Schema({
  name: String,
  conversation: {
    type: ObjectId,
    ref: Conversation // `ref` is a **Model class**, not a string
  }
});
const Event = db1.model('Event', eventSchema);

Refrence here

like image 36
Thức Trần Avatar answered Oct 14 '22 13:10

Thức Trần