Created
January 17, 2012 21:51
-
-
Save StevenLooman/1629156 to your computer and use it in GitHub Desktop.
Exposing Mongoose missing ID on save bug
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; | |
var query = models.B.find({}).where('not.gonna', 'happen'); | |
function queryResult(err, docs) { | |
console.log('queryResult'); | |
if (docs.length < 1) { | |
// always true due to query which will not give any results | |
createB(bCreated); | |
} | |
} | |
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 | |
next(null); | |
} | |
query.exec(queryResult); | |
} | |
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
Simpler version, exposing same error, here: https://gist.github.com/1631992