我正在做的NodeJS使用+表達一個簡單的博客應用程序,我可以添加的第一篇文章沒有問題,但是當我嘗試添加第二個後,我得到了自己的錯誤{ MongoError: E11000 duplicate key error collection: restful_blog_app_v2.blogs index: username_1 dup key: { : null }
MongoError:E11000重複鍵錯誤
這是我的架構
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {
type: Date,
default: Date.now
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});
BlogSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Blog", BlogSchema);
這是用戶模式
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String,
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
這是創造新的崗位航線
app.post("/blogs", isLoggedIn, function (req, res) {
req.body.blog.body = req.sanitize(req.body.blog.body);
var title = req.body.blog.title;
var image = req.body.blog.image
var body = req.body.blog.body;
var created = req.body.blog.created;
var author = {
id: req.user._id,
username: req.user.username
}
var newPost = {
title: title,
image: image,
body: body,
created: created,
author: author
}
Blog.create(newPost, function (err, newBlog) {
if (err) {
console.log(err);
res.render("new");
} else {
console.log(newBlog);
res.redirect("/blogs");
}
});
});
我試圖使用下降db.dropDatabase()從蒙戈控制檯整個數據庫,但問題依然存在,不知道現在做什麼
在您的代碼中,用戶名是mongo Schema中的唯一索引。您添加2個具有相同用戶名的帖子,並將其保存到數據庫將導致此錯誤。 – thelonglqd
@thelonglqd你怎麼看到用戶名是mongo模式中的唯一索引? – Tolsee
index:username_1 dup key:{:null}這個錯誤表明用戶名字段是唯一索引,並且您已經在數據庫中有一個空值,因此當您存儲另一個空值來唯一索引數據庫中的字段時,會拋出此錯誤...請參閱此答案http://stackoverflow.com/a/24430345/6880789 – Tolsee