簡體   English   中英

在 mongoose 中創建帶有 { strict: false } 的文檔

[英]Creating a document with { strict: false } in mongoose

任務是將一些文檔存儲到 MongoDB 中。 這些文檔具有相同的頂層,但從那里它們可能會有所不同。 有效載荷的結構是:

{
  "types": "a", //the type can be "a", "b" or "c"
  "details" : {
       ... // the details object structure is different for each type
    }
}

這是我寫的 model:

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 object 但在架構中添加{ strict: false }來解決問題。 像這樣:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM