Skip to content

Instantly share code, notes, and snippets.

@StevenLooman
Created January 17, 2012 21:51
Show Gist options
  • Save StevenLooman/1629156 to your computer and use it in GitHub Desktop.
Save StevenLooman/1629156 to your computer and use it in GitHub Desktop.
Exposing Mongoose missing ID on save bug
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();
@StevenLooman
Copy link
Author

Simpler version, exposing same error, here: https://gist.github.com/1631992

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