【问题标题】:How can I set composite primary key in mongodb through mongoose如何通过猫鼬在mongodb中设置复合主键
【发布时间】:2014-05-24 03:23:41
【问题描述】:

我想为mongodbmongoose 的集合中的两个字段设置主键。我知道将mongodb 中的复合主键设置为

db.yourcollection.ensureIndex( { fieldname1: 1, fieldname2: 1 }, { unique: true } )

但我使用mongoose 处理mongodb 我不知道如何从mongoose 设置复合主键

更新

我用mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true }); 看我的代码

var mongoose = require('mongoose')

var uristring ='mongodb://localhost/fresh';
var mongoOptions = { db: { safe: true } };

// Connect to Database
mongoose.connect(uristring, mongoOptions, function (err, res) {
    if (err) {
        console.log ('ERROR connecting to: remote' + uristring + '. ' + err);
    } else {
        console.log ('Successfully connected to: remote' + uristring);
    }
});
var mySchema = mongoose.Schema({
        ColorScaleID:String,
        UserName:String,
        Range1:Number,
    })
mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true });
var freshtime= mongoose.model("FreshTimeColorScaleInfo",mySchema)
var myVar = new freshtime({
        ColorScaleID:'red',
        UserName:'tab',
        Range1:10
    })
myVar.save()
mongoose.connection.close();

当我第一次执行此代码时,我在 mongodb 的新数据库中看到一行 {"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }。当我第二次执行相同的代码时,我看到两条相同的行。

{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }
{"_id":...,ColorScaleID:'red',UserName:'tab',Range1:10 }

如果composite primary key 工作,那么它不应该允许我第二次插入相同的数据。会有什么问题?

【问题讨论】:

  • @JohnnyHK 我已经更新了我的问题,你能再看一下吗。
  • 我在 mongodb shell 中实现了与 mongodb 查询相同的功能是 db.person.ensureIndex({ ColorScaleID: 1, UserName: 1}, { unique: true }),但不是使用 mongoose mySchema.index({ ColorScaleID: 1, UserName: 1}, { unique: true })
  • @JohnnyHK - 我不认为这是重复的,因为他的定义是正确的,但这对他不起作用。
  • @Guy - 当时是这样,但从那以后它已经更新了。

标签: javascript node.js mongodb mongoose


【解决方案1】:

也许你可以在你的猫鼬模式模型中尝试这个,

const AppSchema1 = new Schema({
  _id         :{appId:String, name:String},
  name        : String
});

【讨论】:

    【解决方案2】:

    正如大家提到的,你必须使用 Schema 的 index 方法来设置复合唯一键。 但这还不够,之后尝试重新启动 MongoDB。

    【讨论】:

      【解决方案3】:

      您定义架构的方式是正确的并且可以正常工作。您可能遇到的是数据库已经创建并且该集合可能已经存在,即使它可能是空的。 Mongoose 不会重新适应索引。

      作为实验,将您的数据库设置为不存在的数据库。例如:

      var uristring ='mongodb://localhost/randomname';
      

      然后尝试对这个数据库运行这两行代码,看看是否仍然可以插入这两个文档。

      然后比较每个集合中“system.indexes”集合的内容。您应该看到 randomname db 正确设置了复合索引。

      【讨论】:

      • 这仍然不适用于我处理新数据。我如何删除集合,这有点担心我以后想添加一个键,它完全被忽略了?
      猜你喜欢
      • 2015-02-28
      • 1970-01-01
      • 2016-04-29
      • 2013-10-02
      • 1970-01-01
      • 2011-03-18
      • 2018-10-30
      • 1970-01-01
      相关资源
      最近更新 更多