在猫鼬中创建带有{strict:false}的文档

时间:2020-04-21 18:24:35

标签: javascript node.js mongodb mongoose

任务是将一些文档存储到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,但没有保存任何详细信息。

这也是保存详细信息的一种方法吗?

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题,而不是像上面那样创建另一个Details对象,而是在模式内部添加了{ strict: false }。像这样:

const MyOrder = new Schema(
  {
    types: {
      type: String,
      enum: ['a', 'b', 'c'],
    },
  },
  { strict: false }
);

module.exports = Order = mongoose.model('myOrder', MyOrder);