如何在 Mongoose 中定义一个不同于 _id 的主键?

How do I define a different primary key other than _id in Mongoose?

我想用不是 _id 的主键定义 Mongoose 模式。该文档说它只允许在子文档中将架构选项标志 _id 设置为 false。另外,我希望主键是 String 而不是 ObjectId。这可能吗?

使用二级索引是一种选择,但不是一个很好的选择,因为我想要具有专有名称的主键。我也不想 fiddle 在不需要的时候使用两个不同的索引。

这将 documentId 设置为二级索引,但这使得主键无用,因为我只想 select by documentId 而不是任何 _id 最终成为设置为自动。

const DocumentSchema = new Schema({
  documentId: { type: String, index: true }
})

我想做类似

的事情
const DocumentSchema = new Schema({
  documentId: String
})

然后告诉它使用documentId作为主键。

澄清:我特别不想使用 _id 作为键,因为它有一个无用的名称,我想使用 documentId作为主键。

在MongoDB中没有主键。

您只需要一个 unique: true 索引就可以了。

const DocumentSchema = new Schema({
  _id: false,
  documentId: {
    type: String,
    unique: true,
    required: true
  }
})

https://mongoosejs.com/docs/schematypes.html and https://docs.mongodb.com/manual/core/index-unique/

A unique index ensures that the indexed fields do not store duplicate values; i.e. enforces uniqueness for the indexed fields. By default, MongoDB creates a unique index on the _id field during the creation of a collection.

您可以在架构阶段手动定义 _id 字段,例如:

const DocumentSchema = new Schema({
  _id: String //or number, or (increment) function,
  ...
  other_field: BSON_type,
})

已更新 Nestjs

要手动覆盖或定义架构中的 _id 字段,请使用此示例:

/**
 * extends Document is a Mongoose Document from 'mongoose'
 * and don't forget about Nest Schema decorator
 */
@Schema()
export class Key extends Document { 
  @Prop({ type: String }) // also can be Number, or Decimal128
  _id: string; // number

  @Prop({ type: String, required: true })
  secret: string;
}

通过 @Prop({ _id: false })

@Prop 中的子文档禁用 _id

如果您正在寻找带有 _id 示例的嵌入式文档数组,您

并在 insert 阶段之前将 _id 值添加到您的文档或通过您的函数生成它,或 npm 模块,如 thisschema 部分。您唯一需要确保的是,您自定义生成的 _id 值必须是唯一的。如果他们不这样做,mongo returns 你是一个错误,在插入文档 w/o 唯一 _id 值的过程中。

const Schema = new Schema({
  _id: false,
  Id: {
    type: String,
    unique: true,
    index: true,
    required: true,
  },
});

索引将是最好的方法。事实上,_id 也是一个索引。尝试创建如下索引:

documentSchema.index({ 'documentId' : 1 }, { unique: true });

参考:https://docs.mongodb.com/manual/indexes/