无法在 MongoDB 中插入超过 1 个条目

Unable insert more than 1 entry in MongoDB

这是我的架构。 user_id 和 other_id 应该是唯一的(复合)。

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)

这是我的 server-side 代码。使用 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 个。我也删除了索引,但仍然无法正常工作。顺便说一句 'user_id' 在另一个 Collection 中是独一无二的。当我登录 console.log(err) 时,我也没有收到任何错误。

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

这里是友谊指数collection。

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

您想要的是 "combination" 字段在这里 "unique" 而不是单独处理。

这意味着您的模式应该这样定义:

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() 以删除任何会干扰正确操作的 "unique" 索引。

有关详细信息,另请参阅核心文档中的 .createindex() and "Unique Indexes"