【问题标题】:Combination of multiple column unique mongoose nodejs组合多列唯一mongoose nodejs
【发布时间】:2015-09-07 21:08:28
【问题描述】:

目标

为两列创建唯一性

我尝试了什么

这是我的架构,

var mongoose = require('mongoose');

// location table Schema

var locationSchema = new mongoose.Schema({

    locationId: { type: String, required: true },
    stockingLocationId: { type: String, required: true},
    parentStockingLocationId: { type: String },
    stockingLocationDescription: { type: String },
    created: { type: Date, default: Date.now  },
    lastModified: { type: Date, default: Date.now },
    isActive: { type: Boolean , default : true },
    isDeleted: { type: Boolean , default : false }

});

两列是locationIdstockingLocationId

我试过locationSchema.index({locationId:1, stockingLocationId:1}, { unique: true });

但不起作用,

有什么帮助吗?

【问题讨论】:

  • 你能告诉我为什么是负面的吗?
  • @ramamoorthy-villi 代码是正确的。一旦删除数据库并重新启动服务器。然后检查它是否工作!
  • @Vishnu,谢谢,在我添加 index:true 后,它正在工作,例如 locationId: { type: String, required: true,index:true }, stockingLocationId: { type: String, required: true,index :true} 在架构中

标签: node.js mongodb mongoose


【解决方案1】:

我认为您必须分别调用这两列。你这样做的方式,两列的组合将是唯一的(组合的唯一键)。

locationSchema.index({locationId:1}, { unique: true });
locationSchema.index({stockingLocationId:1}, { unique: true });

【讨论】:

  • @ramamoorthy_villi 没问题
  • 我想要这两个字段的组合
【解决方案2】:

更改索引架构后,您需要删除数据库

【讨论】:

  • 我投了反对票,但后来意识到它确实有效。
【解决方案3】:

我知道这有点晚了,但大致上是这样的......

mySchema.index({field1: 1, field2: 1}, {unique: true});

here中指定

【讨论】:

    【解决方案4】:

    在像下面这样的字段周围添加单引号后,它对我有用

    mySchema.index({'field1': 1, 'field2': 1}, {unique: true});
    

    【讨论】:

    • 在字段名称中添加引号后为我工作。干杯!
    • 两件事:这应该是官方答案,而且应该解雇 mongoose 开发人员。
    • @FerMartin 这与 Mongoose 开发人员无关;这就是所有all objects work in Javascript
    • @Mike 我相信 'filed1' 是 javascript 中的有效标识符,因此按照您的链接,应该没有任何区别,对吗?
    • @FerMartin 这是正确的。只要您的对象属性名称是有效的标识符名称,您就不需要在它们周围加上引号。
    【解决方案5】:

    您可以在架构本身中将其设置如下:

     locationId: { type: String, required: true, unique:true, index:true },
     stockingLocationId: { type: String, required: true, unique:true, index:true},
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2018-10-08
      • 2016-11-30
      • 1970-01-01
      • 2013-04-10
      相关资源
      最近更新 更多