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

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