以下是開發(fā)個人博客的評論功能時的主要代碼:
-評論的數(shù)據(jù)模型代碼
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var CommentSchema = new Schema({
blog:{type: ObjectId, ref: 'Blog'},
from:{type: ObjectId, ref: 'User'},
to:{type: ObjectId, ref: 'User'},
content: String,
meta:{
createAt: {
type: Date,
default: Date.now()
},
updateAt:{
type: Date,
default: Date.now()
}
}
});
-nodeJs存儲頁面post過來的信息代碼
comment.save(function(err,blog){
if(err){
console.log(err);
}
res.redirect('/blog/'+ blogId);
});
當(dāng)存入第一條數(shù)據(jù)時,正常。存入第二條時打印出mongo報的如下錯誤:
{ MongoError: E11000 duplicate key error collection: myblog.comm
ents index: name_1 dup key: { : null }...}
報錯后瀏覽了很多網(wǎng)站均無果沸停,此時我的內(nèi)心是崩潰的件豌。在放棄的邊緣苦苦掙扎著傲宜,或許是因?yàn)閳猿值玫搅嘶貓蟀愣选=K于在一個國外?(反正全是英文,但域名為.com)的網(wǎng)站上找到了錯誤的原因以及解決的方法院水。在這腊徙,我想向大家推薦一個不錯的網(wǎng)站http://stackoverflow.com/ 我就是在這里得到了解救。
報錯的原因:
從報錯信息來看是說保存到comments文檔中的主鍵name_1值為null.雖然很顯然在以上代碼里我并沒有將name設(shè)置為主鍵檬某。
解決方法
此時打開mongo
控制臺撬腾,輸入db.comments.getIndexes()
后,返回了一個包含4個對象的數(shù)組恢恼,說明在comments這個文檔中我的主鍵有4個民傻,再使用db.comments.dropIndex({"name":1})
,語句刪除name
主鍵场斑,依次刪除其他兩個主鍵漓踢,只留_id
主鍵。
接下來就是見證奇跡的時刻了漏隐。
輸入評論喧半,發(fā)表。數(shù)據(jù)庫里保存成功青责。