【问题标题】:Trying to populate an object inside another object that is inside another object (NODE.JS)试图在另一个对象内的另一个对象内填充一个对象(NODE.JS)
【发布时间】:2019-05-18 21:59:22
【问题描述】:

此函数获取特定的“进程”,并在 json 中显示以下信息:(POSTMAN)

{
    "process": {
        "_id": "5c18e8d1d4817811839d43d2",
        "name": "Dyeing",
        "colour": {
            "_id": "5c18c972b39bb20769288e8f",
            "name": "azul",
            "category": "5c18c09f4c6baf05ea621bca",
            "__v": 0
        },
        "__v": 0
    },
    "request": {
        "type": "GET",
        "url": "http://localhost:3000/process"
    }
}

过程控制器功能

   exports.process_get_process = (req, res, next) => {
    Process.findById(req.params.processId)
      .populate("colour")
      .populate("category")
      .exec()
      .then(process => {
        if (!process) {
          return res.status(404).json({
            message: "Process not found"
          });
        }
        res.status(200).json({
          process: process,
          request: {
            type: "GET",
            url: "http://localhost:3000/process"
          }
        });
      })
      .catch(err => {
        res.status(500).json({
          error: err
        });
      });
};

“流程”的模型是以下架构:

const mongoose = require('mongoose');

const processSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: { type: String, required: true },
    price: { type: Number, required: false },
    colour: { type: mongoose.Schema.Types.ObjectId, ref: 'Colour', required: false },
});

module.exports = mongoose.model('Process', processSchema);

这是颜色模型: 如您所见,对象“类别”在“颜色”内部,我也想在“过程”对象中显示他。

const mongoose = require('mongoose');

const colourSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: { type: String, required: true },
    category: { type: mongoose.Schema.Types.ObjectId, ref: 'Category', required: true },
});

module.exports = mongoose.model('Colour', colourSchema);

问题:“颜色”内部存在一个“类别”对象,但只显示类别 id,我希望他显示所有类别信息。如何填充它?

【问题讨论】:

    标签: node.js mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    您可以将其指定为populate 函数的选项。

    Process.findById(req.params.processId)
          .populate({
               path: 'colour',
               populate: { path: 'category' }
           })
          .exec()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-19
      • 2022-11-26
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多