如何在mongoose中编写键值对对象Schema



我已经努力创建这样的模式,但还没有得到解决方案。

我试着做这样的事。

questions: {
type: new Schema({
questionId: {
type: String,
},
correct: {
type: Boolean,
},
}),
},

我需要的输出是:

questions: {
[questionId1]:[boolean],
[questionId2]:[boolean]
}

示例:

questions:{
23:true,
29:false
}

提前感谢。

正如saksh73已经指出的那样,Schema可以用Map完成(https://mongoosejs.com/docs/schematypes.html#maps)

const Example = new Schema({
// your stuff
questions: {
type:Map,
of: Boolean
}
});

您可以使用以下方法添加布尔键值对:

const abc = new Schema({
questionId: {
type: Map,
of:Boolean
},
});

如果你想要一个对象而不是布尔值。。。你可以这样做:

const abc = new Schema({
questionId: {
type: Map,
of:new Schema({
id: Number,
title: String,
}),
},
});

最新更新