Node.js 多列唯一mongoose节点的组合
目标 为两列创建唯一性的步骤 我尝试的 这是我的模式Node.js 多列唯一mongoose节点的组合,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,目标 为两列创建唯一性的步骤 我尝试的 这是我的模式 var mongoose = require('mongoose'); // location table Schema var locationSchema = new mongoose.Schema({ locationId: { type: String, required: true }, stockingLocationId: { type: String, required: true}, paren
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 }
});
两列是locationId
和stocklocationid
我尝试了locationSchema.index({locationId:1,stocklocationid:1},{unique:true})代码>
但不管用
有什么需要帮忙的吗?我想你得分别打两个栏目的电话。按照这种方式,两列的组合将是唯一的(组合唯一键)
您需要在更改索引模式后删除数据库我知道有点晚了,但大致上是这样的
mySchema.index({field1: 1, field2: 1}, {unique: true});
如中所述,在如下字段周围添加单引号后,它对我有效
mySchema.index({'field1': 1, 'field2': 1}, {unique: true});
您可以在模式本身中将其设置为以下内容:
locationId: { type: String, required: true, unique:true, index:true },
stockingLocationId: { type: String, required: true, unique:true, index:true},
你能告诉我为什么是否定的吗?@ramamoorthy villi代码是正确的。一旦删除数据库并重新启动服务器。然后检查它是否工作@毗瑟奴,谢谢你,在我将index:true-like-locationId:{type:String,required:true,index:true},stocklocationid:{type:String,required:true,index:true}添加到schema@ramamoorthy_villi没问题,我希望在字段名中添加引号后,将这两个字段组合起来。干杯两件事:这应该是官方的答案,而且,猫鼬开发者应该被解雇。@Fermatin这与猫鼬开发者无关;这就是一切。@Mike我相信“filed1”在javascript中是一个有效的标识符,因此在您的链接之后,应该没有任何区别,对吗?@Fermatin这是正确的。只要你的对象属性名是有效的标识符名,你就不需要在它们周围加引号。我投了反对票,但后来意识到它确实有效。
locationId: { type: String, required: true, unique:true, index:true },
stockingLocationId: { type: String, required: true, unique:true, index:true},