【发布时间】:2018-11-17 13:09:45
【问题描述】:
下面的我的代码包含模式和一个 pre('update') 中间件来操作模式的 name 属性。实际上,如果值已存在于项目集合中,我只想为 name 属性添加一个后缀。
const ItemSchema = mongoose.Schema({
...
name : {type : String, required : true, unique : true, trim : true},
...
})
ItemSchema.pre("update", async function() {
let name = this.getUpdate().$set.name;
if (!name) return Promise.resolve();
let count = await ItemModel.find({name}).count().exec();
if(count>0) name = name + "_SOME_SUFFIX_BY_SOME_LOGIC";
this.getUpdate().$set.name = name;
});
ItemSchema.plugin(require('mongoose-unique-validator'));
const ItemModel = mongoose.model('Item', ItemSchema);
module.exports = ItemModel;
当我尝试更新/修补 name 属性时,计数似乎正确获取数字 1 并通过后缀更新名称。之后,我用正确操作的名称正确更新了更新对象中的名称(因此集合中肯定不存在带有后缀的名称)
但是现在,当我尝试更新时,出现以下错误:
验证失败:名称:错误,预计
name是唯一的。价值: `[名称]_SOME_SUFFIX_BY_SOME_LOGIC'
所以它告诉我,新的后缀名称已经存在于数据库中,即使它不存在。
(我已经在数据库中查找了后缀名称,但我可以保证它不存在,因为我在测试集合上运行它,所以还没有很多条目)
节点版本:8.1.1 mongoose 版本:5.1.3 系统:ubuntu 16.04
【问题讨论】: