node.js - Mongoose - 独立唯一约束

标签 node.js mongodb mongoose unique

我试图在一个架构上获得两个独立的唯一约束,但是......

var Game = new Schema({
    name: String,
    shortName: String
})
Game.index({ name: 1, shortName: 1 }, { unique: true })

...始终创建一个复合索引,使下表有效:

name: "Foo", shortName: "Bar";
name: "Foo", shortName: "Foo";

有什么办法可以让这些独特的约束变得独立吗?

最佳答案

来自 unique index documentation :

You can also enforce a unique constraint on compound indexes. These indexes enforce uniqueness for the combination of index keys and not for either key individually.

因此,要实现此目的,您需要在每个字段上创建唯一索引,如下所示:

var Game = new Schema(
  {
    name: { type: String, unique: true }, 
    shortName: { type: String, unique: true }
  }
)

关于node.js - Mongoose - 独立唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43178258/

相关文章:

javascript - Minimongo无法在客户端进行集合排序

javascript - Mongodb 聚合与客户端处理

javascript - Mongoose 填充排序无法正常工作

javascript - 尝试将 session 注入(inject)到 Nodejs 异步函数中的请求主体中

当 localField 为字符串且foreignField 为 ObjectId 格式时,Mongodb $lookup

node.js - Mongoose 更新通过 $set a value if NOT undefined (NodeJS)

javascript - 无法更新 Mongoose 模型

javascript - Node : how to implement isLoggedIn before all routes?

javascript - Router.use 需要中间件功能?

javascript - 为什么 Puppeteer 不支持多次上传?