Mongoose 模型多密钥类型

f1tvaqid  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(141)

我有一个简单的模式

const xpReward = new mongoose.Schema({
   ...,
   receivedFor: {
     type: Object,
     required: true
   }
});

收到的是一个object,它可以有2个键,值可以是{ "articleId": 5}{ "testId": 7}
我想用一个必需的字段扩展这个receivedFor对象,但保留添加articleIdtestId的可能性。
我知道我可以让它像在上面的例子中那样,因为是一个对象并且可以有任何形式,但是我想在那里指定类型,以便在进一步的用法中可以知道。
我在想:

const xpReward = new mongoose.Schema({
   ...,
   receivedFor: {
     learningPath: {
       type: String,
       required: true
     },
     articleId | testId: {
       type: Number,
       required: true
     }
   }
});

我不想使用其他嵌套对象作为

receivedFor: {
   learningPath: {
     type: String,
      required: true
   },
   // in this example, the old receivedFor will become this valueFor
   // this will be just another nested level, one more parent for it
   valueFor: { 
     type: Object,
     required: true
   }
}

这可以做得更好吗?thx

hvvq6cgz

hvvq6cgz1#

可能需要一些钩子来沿着这个,但这是基本的想法。

const xpReward = new mongoose.Schema({
    ...,
    receivedFor: {
        learningPath: {
            type: String,
            required: true
        },
        foreignId: {
            type: Number,
            required: true
        },
        foreignCollection: { // maybe even make it an enum - articleId | testId
            type: String,
            required: true
        }
    }
});

相关问题