Skip to content

Instantly share code, notes, and snippets.

@aheckmann
Created March 12, 2012 18:12
Show Gist options
  • Save aheckmann/2023726 to your computer and use it in GitHub Desktop.
Save aheckmann/2023726 to your computer and use it in GitHub Desktop.
var mongoose = require('./../mongoose');
mongoose.connect('localhost', 'testing_twomodelsForCollection');
var schema1 = new mongoose.Schema({
name: String
}, {collection: 'mystuff'});
var schema2 = new mongoose.Schema({
age: Number
}, {collection: 'mystuff'});
var A = mongoose.model('A', schema1);
var B = mongoose.model('B', schema2);
mongoose.connection.on('open', function () {
console.log('creating..');
A.create({ name: 'first' }, function (err, a) {
if (err) return console.error(err.stack||err);
B.findById(a, function (err, b) {
if (err) console.error(err.stack||err);
console.error('found an A from B!', b);
b.age = 45;
b.save(function (err) {
if (err) console.error(err.stack||err);
console.error('saved!');
A.findById(b, function (err, a) {
if (err) console.error(err.stack||err);
console.error('finished', a);
mongoose.connection.db.dropDatabase(function () {
mongoose.connection.close();
});
});
});
});
})
});
@japrescott
Copy link

once again! mr heckmann out, to save the world! :) many thanks for this gist! didn't know you could define the collection on the schema regardless of its name.
one thing isn't very clear to me though;
if we find something with A (a.findById) and figure out, that its actually B (based on a type field or such) and we want its model with its virtuals, we call b.findById(a, ...), will Mongoose go back to the server to make an actual query or will it be smart enought to just "rewrap" the result in b?
thanks for making such a great fucking lib!

@aheckmann
Copy link
Author

Calling findById will go back to the server. You might instead try:

A.findById(id, function (er, a) {
  if (a is really b) {
    var b = new B;
    b.init(a._doc);
    // use b normally now
  
I think this works as long as you are not using strict schemas. Can't recall if strict drops unknown paths on the floor (I think so).

Glad Mongoose is working for you :)

@japrescott
Copy link

okey, I see. Thanks for your answer! Then letting b populate something isn't possible at this point anymore, right?

@aheckmann
Copy link
Author

correct. we'll change this in the future

@japrescott
Copy link

I figured out, how I could do something in that direction, but I'm not sure how efficient it is. I think I'm now letting mongoose take an additional trip to the mongodb to populate the fileId field, regardless if its set/existent/null;
A.
findById(id).
populate("fileId").
run( function(err, a){
if (a.type==="b"){
var b=new B;
b.init(a._doc);
}
//a would'nt know about the field fileId (and not have it populated)
//b would know about the field fileId and have it populated
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment