簡體   English   中英

Mongoose 填充多個字段

[英]Mongoose Populate Multiple Fields

我正在嘗試像關系數據庫一樣使用 Mongoose。 我有一個需要引用客戶端、用戶和注釋模式的任務模式。

我找到了許多用一種模式填充另一種模式的示例,但沒有一個用於需要填充多個模式的示例。 我嘗試了以下鏈接: https : //mongoosejs.com/docs/populate.html http://ronaldroe.com/populating-multiple-fields-and-levels-with-mongoose/

findAll: function (req, res) {
    Task
      .find(req.query)
      .sort({ date: -1 })
      // populate associated user
      .populate("user", "_id firstName lastName")
      // populate associated client
      .populate("client", "_id name")
      // all notes for the task and when they were created
      .populate("note", "_id content created_at")
      .then(dbModel => {
        res.status(200).json({
          tasks: dbModel.map(model => {
            return {
              _id: model._id,
              user: model.user,
              client: model.client,
              assignDate: model.assignDate,
              assignedStatus: model.assignedStatus,
              completionStatus: model.completionStatus,
              description: model.description,
              note: model.note,
            };
          })
        })
      })
      .catch(err => res.status(422).json(err));
  }

當我對這些數據發出 GET 請求時,我得到以下信息:

"tasks": [
        {
            "_id": "5d6980d8459a8b9f0e133d04",
            "user": [
                {
                    "_id": "5d6afd8a101f355244adfd9a",
                    "firstName": "Dexter",
                    "lastName": "Morgan"
                }
            ],
            "assignDate": "2018-12-09T00:00:00.000Z",
            "assignedStatus": "true",
            "completionStatus": "in-progress",
            "description": "This client needs to be contacted for future sales"
        }
]

我還想獲取客戶端 ID 和名稱以及與此任務相關的所有注釋。

試試下面的代碼:

findAll: function (req, res) {
    Task
      .find(req.query)
      .sort({ date: -1 })
      // populate associated user
      .populate({path : 'user' , select: '_id firstName lastName'}) 
      // populate associated client
      .populate({path : 'client' , select: '_id name'})
      // all notes for the task and when they were created
      .populate({path : 'note' , select : '_id content created_at'})
      .then(dbModel => {
        res.status(200).json({
          tasks: dbModel.map(model => {
            return {
              _id: model._id,
              user: model.user,
              client: model.client,
              assignDate: model.assignDate,
              assignedStatus: model.assignedStatus,
              completionStatus: model.completionStatus,
              description: model.description,
              note: model.note,
            };
          })
        })
      })
      .catch(err => res.status(422).json(err));
  }

暫無
暫無

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

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