Last active
May 10, 2018 05:37
-
-
Save kessiler/4f1dc0e7203a55fadc4e3c817ba379bc to your computer and use it in GitHub Desktop.
Mongoose _populate + post init bug - version 5.18
This file contains 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
#!/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