Why am I getting this error? E11000 duplicate key error collection: reklamaswin.ads index: username_1 dup key: { : null } when I want to make a new ad. I know that there is a duplicate somewhere, but I can't find where is the problem. Here are my schemas that I use in the project and the post request that goes to "/new". I'm creating a new Ad and storing it in the ads collection and then pushing it into the user.ads for the req.user
router.post('/new', middleware.isLoggedIn, function(req, res) {
upload(req, res, function(err) {
if (err) {
req.flash('error', err.message);
return res.redirect('/new');
}
var ad = new Ad({
banner: '/uploads/' + req.file.filename,
url: req.user.url,
paymentType: req.body.paymentType,
transactionId: req.body.transactionId
});
ad.save(function(err, ad) {
if (err) {
req.flash('error', err.message);
return res.redirect('/new');
}
User.findById(req.user._id, function(err, user) {
if (err) {
req.flash('error', err.message);
return res.redirect('/new');
}
user.ads.push(ad);
user.save(function(err, ad) {
if (err) {
req.flash('error', err.message);
return res.redirect('/new');
}
req.flash('success', 'Successfully added new ad.');
res.redirect('/');
});
});
});
});
});
This is the Ad schema.
var AdSchema = new mongoose.Schema({
banner: String,
likes: {
type: Number,
default: 0
},
url: String,
paymentType: {
type: String,
default: 'free'
},
transactionId: String,
sponsored: {type: Boolean, default: false}
});
This is the User schema.
var UserSchema = new mongoose.Schema({
username: {
type: String,
trim: true
},
email: {
type: String,
trim: true,
unique: true
},
password: String,
joined: {
type: Date,
default: Date.now
},
siteRole: {
type: String,
default: 'user'
},
ads: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Ad'
}
]
});