簡體   English   中英

es6 擴展運算符 - 貓鼬結果副本

[英]es6 spread operator - mongoose result copy

我正在用 mongo DB 和 mongoose 開發一個 express js API。

我想在 Javascript es6 中創建一個由幾個變量和貓鼬請求的結果組成的對象,並希望使用 es6 擴展運算符來執行此操作:

MyModel.findOne({_id: id}, (error, result) => {
   if (!error) {
      const newObject = {...result, toto: "toto"};
   }
});

問題是應用擴展運算符以一種奇怪的方式對其進行轉換:

newObject: {
   $__: {
      $options: true,
      activePaths: {...},
      emitter: {...},
      getters: {...},
      ...
      _id: "edh5684dezd..."
   }
   $init: true,
   isNew: false,
   toto: "toto",
   _doc: {
      _id: "edh5684dezd...",
      oneFieldOfMyModel: "tata",
      anotherFieldOfMyModel: 42,
      ...
   }
}

我有點理解,貓鼬豐富了對象結果以允許與它進行特定的交互,但是當我在執行此操作之前使用 console.log 時,它描繪了一個沒有所有這些東西的簡單對象。

我不想通過...result._doc作弊,因為我抽象了這部分,它不適合這種方式。 也許有一種方法可以復制沒有豐富內容的對象。

感謝您的時間。

您可以使用 Mongoose Document.toObject()方法。 它將返回從數據庫中獲取的底層純 JavaScript 對象。

const newObject = {...result.toObject(), toto: "toto"};

您可以在 此處閱讀有關.toObject()方法的更多信息。

對於某人可能會有所幫助:

const newObject = {
    ...JSON.parse(JSON.stringify(result)),
    toto: "toto"
};

但是,如果您在架構中使用日期、函數、未定義、正則表達式或無窮大,則會受到限制

我遇到了同樣的問題,並找到了除先前答案之外的一些替代方案。

選項 1 Object.assign()

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

例子:

Object.assign(result, {toto: "toto");

選項 2 Document.prototype.set()

Sets the value of a path, or many paths.

doc.set("toto", "toto")


暫無
暫無

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

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