在mongoose中组合两个模型属性生成唯一键哈希可以通过创建虚拟属性和pre-save钩子来实现。下面是一个示例代码:
首先,我们需要引入mongoose库和crypto库:
const mongoose = require('mongoose');
const crypto = require('crypto');
接下来,创建两个模型,假设一个是User模型,另一个是Product模型。我们想要组合User的email属性和Product的name属性生成唯一键哈希:
// 创建User模型
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true
},
// 其他属性...
});
const User = mongoose.model('User', userSchema);
// 创建Product模型
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
// 其他属性...
});
const Product = mongoose.model('Product', productSchema);
然后,在Product模型中创建一个虚拟属性来保存组合属性的唯一键哈希:
productSchema.virtual('uniqueKey').get(function () {
const email = this.user.email; // 假设Product模型有一个user属性,关联到User模型
const name = this.name;
const hash = crypto.createHash('md5').update(email + name).digest('hex');
return hash;
});
接下来,在Product模型的pre-save钩子中使用该虚拟属性来确保唯一键哈希的唯一性:
productSchema.pre('save', async function (next) {
const product = await Product.findOne({ uniqueKey: this.uniqueKey });
if (product) {
const error = new Error('Duplicate unique key');
// 处理错误...
next(error);
} else {
next();
}
});
现在,当你保存一个Product实例时,mongoose会自动调用pre-save钩子并生成唯一键哈希。如果唯一键哈希已存在于数据库中,则会触发错误。
这样,你就可以在mongoose中组合两个模型属性生成唯一键哈希了。请注意,以上代码只是示例,你需要根据你的具体模型和业务逻辑进行调整。
参考文档:
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云