我使用mongoose来定义2个模式。
employee.js
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
const Role = require("./role");
const employeeSchema = mongoose.Schema({
code: { type: String, required: true, unique: true, index: true },
names: { type: String, required: true },
last_names: { type: String, required: true },
role: Role.schema,
dui: { type: String, required: true, unique: true, index: true },
nit: { type: String, required: false, unique: true, index: true },
sex: { type: String, required: false },
civil_status: { type: String, required: false },
birthday: { type: Date, required: false },
telephone: { type: String, required: true },
city: { type: String, required: true },
address: { type: String, required: true },
active: { type: Boolean, required: true },
});
employeeSchema.plugin(uniqueValidator);
module.exports = mongoose.model("Employee", employeeSchema);
和role.js
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
const roleSchema = mongoose.Schema({
code: { type: String, required: true, unique: true, index: true },
description: { type: String, required: true }
});
roleSchema.plugin(uniqueValidator);
module.exports = mongoose.model("Role", roleSchema);
我遇到的问题是,每当我插入一个角色代码重复的文档时,都会因为唯一验证而得到一个错误。
roleSchema.plugin(uniqueValidator);
js中,我还尝试使用.set来更改role中的字段。
const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");
const Role = require("./role");
const subRole = Role.schema.clone().set('code', {unique: false}).set('code', {index : false});
const employeeSchema = mongoose.Schema({
code: { type: String, required: true, unique: true, index: true },
names: { type: String, required: true },
last_names: { type: String, required: true },
role: subRole,
dui: { type: String, required: true, unique: true, index: true },
nit: { type: String, required: false, unique: true, index: true },
sex: { type: String, required: false },
civil_status: { type: String, required: false },
birthday: { type: Date, required: false },
telephone: { type: String, required: true },
city: { type: String, required: true },
address: { type: String, required: true },
active: { type: Boolean, required: true },
});
employeeSchema.plugin(uniqueValidator);
module.exports = mongoose.model("Employee", employeeSchema);
我总是得到一个错误,说角色代码需要是唯一的。我是不是用错了.set?还是我遗漏了什么?提前非常感谢。
1条答案
按热度按时间mrfwxfqh1#
通过变更解决:
到
删除了雇员的集合,这样它就可以用正确的索引重新创建它,这就成功了。
在github的一个mongoose期刊中提到了这一点:https://github.com/Automattic/mongoose/issues/11547
据说他们实施了一些关于它的东西,但我没有得到它。