2017-05-22 67 views
0

這是我的模式。 user_id和other_id應該是唯一的(複合)。無法在MongoDB中插入超過1個條目

var mongoose = require("mongoose"); 
var uniqueValidator = require('mongoose-unique-validator'); 

var Schema = mongoose.Schema; 

var FriendshipSchema = new Schema({ 

    user_id: { 
    type: String, 
    default: "", 
    trim: true, 
unique:true, 
    }, 
    other_id: { 
    type: String, 
    default: "", 
unique:true, 
    }, 

    status: { 
    type: String, 
    index: true, 
    default: "none", 
    }, 

}); 
FriendshipSchema.plugin(uniqueValidator); 

module.exports = mongoose.model('Friendship', FriendshipSchema) 

這裏是我的服務器端代碼。使用Mongoose非常簡單的插入。

app.post('/api/user/friendrequest', function(req, res){ 
var friendship = new Friendship(req.body); 
console.log(req.body); 

Friendship.find({}, function (err, docs) { 
     if (docs.length){ 
console.log('abac'); 
     }else{ 
      friendship.save(function(err){ 

      if (err) 
      { 
      console.log(err) 
      } 
      }); 
     } 
    }); 
    }); 

我在控制檯中得到這個響應,但是在MongoDB中保存了不超過1個條目。我刪除了索引,但仍然無法正常工作。 btw'user_id'在另一個Collection中是唯一的。我也沒有得到任何錯誤,當我登錄console.log(錯誤)。

{ user_id: 'google-oauth2|117175967810648931400', 
    status: 'pending', 
    other_id: 'facebook|10209430751350509' } 
abac 

以下是友誼集合的索引。

db.friendships.getIndexes() 
[ 
     { 
       "v" : 2, 
       "key" : { 
         "_id" : 1 
       }, 
       "name" : "_id_", 
       "ns" : "kola.friendships" 
     } 
] 

回答

1

你想要的是在這裏「唯一」字段的「組合」,而不是單獨對待。

這意味着你的模式應該改爲定義是這樣的:

var FriendshipSchema = new Schema({ 

    user_id: { 
    type: String, 
    default: "", 
    trim: true, 
    }, 
    other_id: { 
    type: String, 
    default: "", 
    }, 

    status: { 
    type: String, 
    index: true, 
    default: "none", 
    }, 

}); 

// Instead define the schema level index here 
FriendshipShema.index({ "user_id": 1, "other_id": 1 },{ "unique": true }); 

module.exports = mongoose.model('Friendship', FriendshipSchema); 

這樣做的最好的部分是,你不需要任何插件來支持你想要做什麼。

請確保您在集合上運行.dropIndexes()以擺脫會干擾正確操作的任何單個「唯一」索引。

另請參閱.createindex()"Unique Indexes"的核心文檔以獲取更多信息。

+0

我丟棄了表,刪除了_id_以外的所有索引,但仍然只能添加1個條目,但仍然沒有錯誤。然而,在一個階段,我得到了這個'驅動程序:真的, 代碼:11000, 索引:0, errmsg:'E11000重複鍵錯誤收集:kola.friendships索引:user_id_1_other_id_1 dup鍵:{:「google-oauth2 | 117175967810648931400 「,:」google-oauth2 | 109598513284156650220「}', getOperation:[Function], toJSON:[Function], toString:[Function]}' –

+0

@AlamgirQazi好的,那是設計。你只能有**一個**字段的組合。你在期待什麼? –

+0

我有5個用戶A,B,C,D,E,每個用戶都有不同的user_id。對於一個記錄,我想要AB,對於我想要的AC等,因爲每個人都有獨特的鍵,我應該能夠將它們添加正確嗎? –