Created
March 12, 2012 18:12
-
-
Save aheckmann/2023726 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
}); | |
}); | |
}); | |
}) | |
}); |
okey, I see. Thanks for your answer! Then letting b populate something isn't possible at this point anymore, right?
correct. we'll change this in the future
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
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 :)