Skip to content

Instantly share code, notes, and snippets.

@kessiler
Last active May 10, 2018 05:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kessiler/4f1dc0e7203a55fadc4e3c817ba379bc to your computer and use it in GitHub Desktop.
Save kessiler/4f1dc0e7203a55fadc4e3c817ba379bc to your computer and use it in GitHub Desktop.
Mongoose _populate + post init bug - version 5.18
#!/usr/bin/env node
'use strict';
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const { connection, Schema } = mongoose;
const UserSchema = new Schema({
name: {
type: String
},
_organization: {
type: Schema.Types.ObjectId, ref: 'Organization'
}
});
const OrganizationSchema = new Schema({
_admin: { type: Schema.Types.ObjectId, ref: 'User' },
meta: {
enabledUsers: { type: Number }
}
});
OrganizationSchema.post('init', function () {
this.meta.enabledUsers = 0;
});
const UserModel = mongoose.model('User', UserSchema);
const OrganizationModel = mongoose.model('Organization', OrganizationSchema);
const user = new UserModel({ name: 'Igor' });
const org = new OrganizationModel({ _admin: user._id });
user._organization = org._id;
async function run() {
await connection.dropDatabase();
await user.save();
await org.save();
let crash = await UserModel.findById(user).populate('_organization');
console.log(crash);
return connection.close();
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment