【问题标题】:How to avoid duplicate entries in mongoose如何避免猫鼬中的重复条目
【发布时间】:2017-06-23 07:43:02
【问题描述】:

我正在 mongoose 中创建一个新架构并尝试从用户那里获取输入。我希望不会为 serverIP 更新重复条目,因为添加了 unique : true。但这并没有按预期工作,并且重复条目正在通过。

下面是示例代码:-

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var ServerSchema = new Schema({
    serverIp: { type : String , unique : true },
    Name:  { type: String },
    serverType: {type: String , required : true },
    created_date: {type: Date, default: Date.now},
    updated_date: {type: Date, default: Date.now}
});

我已经检查了CreateIndex 的功能,但不知道如何用我的代码实现它。

我从来没有做过后端部分,所以如果这是一个新手问题,请原谅。

【问题讨论】:

    标签: json node.js mongodb mongoose


    【解决方案1】:

    尝试在字段serverIp上创建唯一索引,

    ServerSchema.index({serverIp: 1}, {unique: true});
    

    【讨论】:

      【解决方案2】:

      在 db 中插入一些记录后,您似乎已经完成了唯一索引(在架构级别)。

      请按照以下步骤避免重复。

      1) 删除你的数据库:

      $ mongo

      > use <db-name>;
      
      > db.dropDatabase();
      

      2) 现在在架构级别进行索引,您已经完成了。

      它将避免使用相同字段 serverIp(在您的情况下)值的重复记录插入。

      为了保证索引,使用命令

      > db.db_name.getIndexes()
      

      【讨论】:

        【解决方案3】:

        您必须在创建架构后重新启动 mongo。

        【讨论】:

        • 试试serverIp: { type: String, index: { unique: true } }
        【解决方案4】:

        我在尝试为我的文章标题添加 unique: true 时遇到了同样的问题。我删除了数据库,重新启动了本地服务器并在终端中重新启动了 mongo。那是唯一对我有用的东西。

        【讨论】:

          猜你喜欢
          • 2019-01-07
          • 2023-03-22
          • 2014-06-17
          • 1970-01-01
          • 1970-01-01
          • 2012-08-24
          • 1970-01-01
          • 2022-01-08
          相关资源
          最近更新 更多