任务是将一些文档存储到MongoDB中。这些文档具有相同的顶层,但是从那里可以有所不同。有效负载的结构为:
{
"types": "a", //the type can be "a", "b" or "c"
"details" : {
... // the details object structure is different for each type
}
}
这是我写的模型:
const Details = { strict: false };
const MyOrder = new Schema({
types: {
type: String,
enum: ['a', 'b', 'c'],
},
details: Details,
});
module.exports = Order = mongoose.model('myOrder', MyOrder);
我使用{ strict: false }
设置了详细信息,因为无论结构如何,我都希望获取其数据。也许那是错的。
完成POST请求后,将文档保存到数据库中,如下所示:
_id: ObjectId("...")
types: "a"
__v : 0
它保存了types
,但不保存细节。
也是保存详细信息的一种方法吗?
我设法通过不创建如上所述的另一个Details
对象,而是在模式内部添加{ strict: false }
来解决该问题。像这样:
const MyOrder = new Schema(
{
types: {
type: String,
enum: ['a', 'b', 'c'],
},
},
{ strict: false }
);
module.exports = Order = mongoose.model('myOrder', MyOrder);