有条件跳过mongoose钩function

我有一个预保存挂钩来encryptionUser架构的password字段,如:

 var schema = new mongoose.Schema({ username: 'string', password: 'string' }); schema.pre('save', encrptPasswordHook); schema.pre('update', encrptPasswordHook); schema.pre('findOneAndUpdate', encrptPasswordHook); ... 

通过这种方式,每次User创build或更新时,我都在我的数据库中encryption了密码string。

现在我有一个旧的User数据与encryption密码的JSON文件。 我想使用这个User模型将JSON文件导入到我的数据库中。

如何避免预存钩再次encryption密码?

您可以使用User.collection.insert()来绕过所有的Mongoosevalidation(插入的数据的types将不会被检查)和挂钩,它直接使用MongoDB驱动程序:

 var UserSchema = new mongoose.Schema({ username: 'string', password: 'string' }); var User = mongoose.model('User', UserSchema); User.collection.insert({ username: 'Some Name', password: 'The Encrypted Password' });