我有一个标签模式(用猫鼬定义):
var Tag = new Schema({
_id: String // Not ObjectId but the name of the tag.
});
我想使用标签名称作为它的_id,但我不想用名称来操作这个字段_id。例如,我想添加一个带有代码的新标签,new Tag({name: 'tagA'})而不是new Tag({_id: 'tagA'}). 由于代码以这种方式更具表现力。
所以我需要更改name为_id. 一种方法是使用预保存挂钩。
Tag.pre('save', function(next) {
if (!this._id && this.name) this._id = this.name;
next();
});
有没有比这个更好的方法?