-
-
Save pauliusuza/4450461 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'); | |
var Schema = mongoose.Schema; | |
var assert = require('assert') | |
console.log('\n==========='); | |
console.log(' mongoose version: %s', mongoose.version); | |
console.log('========\n\n'); | |
mongoose.set('debug', true); | |
mongoose.connect('localhost', 'testing_prepopulate'); | |
mongoose.connection.on('error', function () { | |
console.error('connection error', arguments); | |
}); | |
// user model | |
var userSchema = Schema({ name: 'string' }); | |
var User = mongoose.model('User', userSchema); | |
// A model | |
var schema = new Schema({ | |
name: String | |
, _self: { type: Schema.ObjectId, ref: 'User' } | |
}); | |
schema.pre('init', function (next, doc, query) { | |
// hack | |
query.populate('_self'); | |
next(); | |
}); | |
var A = mongoose.model('A', schema); | |
mongoose.connection.on('open', function () { | |
var u = new User({ name: 'mark' }); | |
u.save(function (err) { | |
if (err) return done(err); | |
var a = new A({ name: 'prepopulate', _self: u }); | |
a.save(function (err, a) { | |
if (err) return done(err); | |
A.findById(a, function (err, doc) { | |
console.error('populated name "%s"', doc._self.name); | |
done(err); | |
}); | |
}) | |
}) | |
}); | |
function done (err) { | |
if (err) console.error(err.stack); | |
mongoose.connection.db.dropDatabase(function () { | |
mongoose.connection.close(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment