如何创建mongo严格模式-嵌套文档与任何字符串键和只有值的数组的ObjectID,作为typescript接口(SchemaForMongo):

k97glaaz  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(139)

我正在使用Nest.js,并尝试为下面的ts创建一个严格的模式:

interface SchemaForMongo {
      [key: string]: ObjectID[]
    }
    
    const invalidDocumentProperty_1: SchemaForMongo = {validKey : mongoose.Types.ObjectId('4edd40c86762e0fb12000003')}  // invalid value
    const invalidDocumentProperty_2: SchemaForMongo = {validKey : ['4edd40c86762e0fb12000003']} // invalid value
    const invalidDocumentProperty_3: SchemaForMongo = {validKey : ['invalid value']} // invalid value
    const invalidDocumentProperty_4: SchemaForMongo = {33 : [mongoose.Types.ObjectId('4edd40c86762e0fb12000003')]} // invalid key
    
    const validDocumentProperty: SchemaForMongo = {validKey: [mongoose.Types.ObjectId('4edd40c86762e0fb12000003')]} // valid key and value
arknldoa

arknldoa1#

我可能是错的,但如果我的记忆力很好,mongoDB不支持字典。(check here
所以我认为你唯一的选择就是做你想做的事情:

interface MongoKeyValuePair {
  key: string
  value: mongoose.types.ObjectId[]
}

export class ModelWithDictionary extends Document {
  @Prop({ type: MongoKeyValuePair, default: [] })
  dictionary: MongoKeyValuePair[]
}

相关问题