Created
January 18, 2012 08:35
-
-
Save StevenLooman/1631992 to your computer and use it in GitHub Desktop.
Exposing Mongoose missing ID on save bug - simpler version
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'); | |
var eyes = require('eyes'); | |
mongoose.connect('mongodb://localhost/null_id'); | |
// schema definition | |
var A = new mongoose.Schema({ | |
f1: String, | |
f2: [ { | |
type: Number, | |
index: true | |
} ], | |
b: { | |
type: mongoose.Schema.ObjectId, | |
ref: B | |
} | |
}); | |
var B = new mongoose.Schema({ | |
f1: String, | |
f2: [ { | |
type: Number, | |
index: true | |
} ] | |
}); | |
// models | |
var models = { | |
A: mongoose.model('A', A), | |
B: mongoose.model('B', B) | |
}; | |
// triggers | |
A.pre('save', connectB); | |
function connectB(next) { | |
console.log('connectB'); | |
var newA = this; | |
eyes.inspect(newA.id, 'new a.id'); | |
function createB(callback) { | |
console.log('createB'); | |
var b = new models.B({ | |
f1: 'b', | |
f2: [ 0, 1, 2 ] | |
}); | |
b.save(callback); | |
} | |
function bCreated(err) { | |
console.log('bCreated'); | |
eyes.inspect(this.id, 'this id'); | |
eyes.inspect(this, 'this'); | |
console.log(this.emitted.complete[0]._id); // <-- this works, but shouldn't it be 'this.id'? this seems like fiddling with internals... | |
newA.b = this; // this will fail, if b would have already existed, this would succeed | |
next(null); | |
} | |
createB(bCreated); | |
} | |
function main() { | |
console.log('main'); | |
var a = new models.A({ | |
f1: 'a', | |
f2: [ 0, 1, 2 ] | |
}); | |
function aSaved(err) { | |
console.log('aSaved'); | |
} | |
a.save(aSaved); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment