mongoose model.create() 不允许重复输入,而模型中的任何键都是“唯一的:'true'”
mongoose model.create() is not allowing duplicate inputs without any key in model being `'unique:'true'`
我正在使用 mongoose 和 nodejs 来插入数据。我正在使用 MVC,在我的控制器中我有这个代码:
module.exports.create_tracsaction = function (req, res) {
Company.findOne({ username: req.body.req_from }, function (err, user) {
if (user.vaccine.extra < req.body.req_vac) {
return res.redirect('/vaccine');
}
else {
var data = {
req_from: req.body.req_from,
req_to: req.body.req_to,
amt_req: req.body.req_vac,
transaction_status: "Awaiting confirmation",
vaccine: user.vaccine.name,
transaction_value: user.vaccine.price * req.body.req_vac
}
Transaction.create(data);
return res.redirect('/vaccine');
}
})
console.log(req.body);
};
这是我的架构
const transactionSchema = new mongoose.Schema({
req_from: {
type: String,
required: true
},
req_to: {
type: String,
required: true
},
amt_req: {
type: Number,
required:true
},
transaction_status: {
type: String,
default: "Awaiting confirmation"
},
vaccine: String,
transaction_value: Number
}, {
timestamps: true
});
尽管没有字段有 属性 unique:'true'
,但我收到此错误:
MongoError: E11000 duplicate key error collection: innovate_dev.transactions index: username_1 dup key: { username: null }
如何消除这个错误?我第一次从视图发送数据时没有错误,但从那以后每次都给出这个错误。
如果您还需要什么,请告诉我。提前致谢 :D
看起来在交易的 username
字段上的某个时间点创建了一个唯一索引。根据您的模式,它不再存在。因此,每次您输入 null 时都会被索引并引发错误。
如果您使用的是 Compass 或其他 GUI,您可以进入并删除它。
否则使用 MongoShell 删除:
use innovate_dev
它将切换到您的数据库
db.transactions.dropIndex('username_1')
我正在使用 mongoose 和 nodejs 来插入数据。我正在使用 MVC,在我的控制器中我有这个代码:
module.exports.create_tracsaction = function (req, res) {
Company.findOne({ username: req.body.req_from }, function (err, user) {
if (user.vaccine.extra < req.body.req_vac) {
return res.redirect('/vaccine');
}
else {
var data = {
req_from: req.body.req_from,
req_to: req.body.req_to,
amt_req: req.body.req_vac,
transaction_status: "Awaiting confirmation",
vaccine: user.vaccine.name,
transaction_value: user.vaccine.price * req.body.req_vac
}
Transaction.create(data);
return res.redirect('/vaccine');
}
})
console.log(req.body);
};
这是我的架构
const transactionSchema = new mongoose.Schema({
req_from: {
type: String,
required: true
},
req_to: {
type: String,
required: true
},
amt_req: {
type: Number,
required:true
},
transaction_status: {
type: String,
default: "Awaiting confirmation"
},
vaccine: String,
transaction_value: Number
}, {
timestamps: true
});
尽管没有字段有 属性 unique:'true'
,但我收到此错误:
MongoError: E11000 duplicate key error collection: innovate_dev.transactions index: username_1 dup key: { username: null }
如何消除这个错误?我第一次从视图发送数据时没有错误,但从那以后每次都给出这个错误。
如果您还需要什么,请告诉我。提前致谢 :D
看起来在交易的 username
字段上的某个时间点创建了一个唯一索引。根据您的模式,它不再存在。因此,每次您输入 null 时都会被索引并引发错误。
如果您使用的是 Compass 或其他 GUI,您可以进入并删除它。
否则使用 MongoShell 删除:
use innovate_dev
它将切换到您的数据库
db.transactions.dropIndex('username_1')