当我尝试将第二个文档插入到我的交易集合中时,我收到了该错误。
架构如下
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TransactionSchema = new Schema({
amount: {
type: Number,
required: true
},
reference: {
type: String,
required: true
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
}
});
TransactionSchema.index({reference:1}, {unique:true});
module.exports = mongoose.model('Transaction', TransactionSchema);
这是我用来插入文档的代码
var trx = new Transaction();
trx.amount = data.metadata.amount;
trx.user = data.metadata.user_id;
trx.reference = req.query.reference;
console.log(trx);
trx.save(function(err) { //save the transaction
if(err) {
console.log(err);
return res.render('transaction_error', {
title: "Payment Error", message: "Oooops....An Error occured while attempting to complete the transaction. Please wait a while and try again"
});
}
console.log(trx)
返回 -
{
reference: '3t3ktloj2j',
user: 5a75a5a9c6e49c2be008b262,
amount: 30000,
_id: 5a8a902e67ddf65790ed5ddb
}
我已经在集合中有一个事务,这个事务与存储中的事务有不同的参考。
当我尝试添加第二个错误时,我一直收到此错误,不知道它来自哪里。
MongoError: E11000 duplicate key error collection: annka.transactions index: assets_1 dup key: { : null }
答案 0 :(得分:0)
此错误表示您正在尝试将重复值保存到具有唯一索引的字段中-这样的字段不能存储重复值。
有关MongoDB中唯一索引的更多信息,请参见:https://docs.mongodb.com/manual/core/index-unique/