发送嵌套对象在GET请求中

huangapple go评论80阅读模式
英文:

Send nested object on GET

问题

以下是翻译好的部分:

我有一个非常基本的模式,其中包含另一个名为Vehicle的对象。

let rentSchema = new Schema({
    code: {
        type: Number
    },
    vehicle: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Vehicle'
    },
    ongoing: {
        type: Boolean,
        default: false
    }
}, {collection: 'RentCollection'});

在控制器中查找所有:

exports.getRent = function (req, res) {
    // 在数据库中查找
    rentSchema.find({}, function (err, rent) {
        if (err) res.status(400).send(err);
     
        res.json(rent);
    });
};

响应作为Rents对象数组返回,但是Vehicle对象缺失在Rent对象中。这是为什么?

_id: "5e04c19d0a0a100f58bd64b5"
__v: 0
ongoing: false
英文:

I have a very basic schema which has another object called Vehicle, inside

let rentSchema = new Schema({
    code: {
        type: Number
    },
    vehicle: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Vehicle'
    },
    ongoing: {
        type: Boolean,
        default: false
    }
}, {collection: 'RentCollection'});

Find all in the controller

exports.getRent = function (req, res) {
    // Find in the DB
     rentSchema.find({}, function (err, rent) {
        if (err) res.status(400).send(err);
     
        res.json(rent);
     });
 };

The response comes as an array of Rents but Vehicle object is missing from the Object Rent. Why is that?

_id: "5e04c19d0a0a100f58bd64b5"
 __v: 0 
ongoing: false

答案1

得分: 1

以下是翻译好的部分:

1-) 首先,您需要创建一个模型并像这样导出它:

rent.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let rentSchema = new Schema(
  {
    code: {
      type: Number
    },
    vehicle: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Vehicle"
    },
    ongoing: {
      type: Boolean,
      default: false
    }
  },
  { collection: "RentCollection" }
);

module.exports = mongoose.model("Rent", rentSchema);

2-) 假设您有这个车辆模型:

vehicle.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let vehicleSchema = new Schema(
  {
    name: String
  },
  { collection: "VehicleCollection" }
);

module.exports = mongoose.model("Vehicle", vehicleSchema);

3-) 首先,让我们在VehicleCollection中创建一个车辆,像这样:

{
    "_id": "5e0f465205515667746fd51a",
    "name": "Vehicle 1",
    "__v": 0
}

4-) 然后,让我们使用这辆车的ID在RentCollection中创建一个租赁文档,如下所示:

{
    "ongoing": false,
    "_id": "5e0f46b805515667746fd51d",
    "code": 1,
    "vehicle": "5e0f465205515667746fd51a",
    "__v": 0
}

5-) 现在,我们可以使用以下代码来将车辆与租赁关联起来。

const Rent = require("../models/rent"); //todo: change to path to the rent.js

exports.getRent = function(req, res) {
  Rent.find({})
    .populate("vehicle")
    .exec(function(err, rent) {
      if (err) {
        res.status(500).send(err);
      } else {
        if (!rent) {
          res.status(404).send("No rent found");
        } else {
          res.json(rent);
        }
      }
    });
};

6-) 结果将是:

[
    {
        "ongoing": false,
        "_id": "5e0f46b805515667746fd51d",
        "code": 1,
        "vehicle": {
            "_id": "5e0f465205515667746fd51a",
            "name": "Vehicle 1",
            "__v": 0
        },
        "__v": 0
    }
]
英文:

Here is step by step explanations to make it work:

1-) First you need to create a model and export it like this:

rent.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let rentSchema = new Schema(
  {
    code: {
      type: Number
    },
    vehicle: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Vehicle"
    },
    ongoing: {
      type: Boolean,
      default: false
    }
  },
  { collection: "RentCollection" }
);

module.exports = mongoose.model("Rent", rentSchema);

2-) Let's say you have this Vehicle model:

vehicle.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let vehicleSchema = new Schema(
  {
    name: String
  },
  { collection: "VehicleCollection" }
);

module.exports = mongoose.model("Vehicle", vehicleSchema);

3-) First let's create a vehicle like this in the VehicleCollection like this:

{
    "_id": "5e0f465205515667746fd51a",
    "name": "Vehicle 1",
    "__v": 0
}

4-) Then let's create a rent document in RentCollection using this vehicle id like this:

{
    "ongoing": false,
    "_id": "5e0f46b805515667746fd51d",
    "code": 1,
    "vehicle": "5e0f465205515667746fd51a",
    "__v": 0
}

5-) Now we can use the following code, to populate the vehicle with the rents.

const Rent = require("../models/rent"); //todo: change to path to the rent.js

exports.getRent = function(req, res) {
  Rent.find({})
    .populate("vehicle")
    .exec(function(err, rent) {
      if (err) {
        res.status(500).send(err);
      } else {
        if (!rent) {
          res.status(404).send("No rent found");
        } else {
          res.json(rent);
        }
      }
    });
};

6-) The result will be:

[
    {
        "ongoing": false,
        "_id": "5e0f46b805515667746fd51d",
        "code": 1,
        "vehicle": {
            "_id": "5e0f465205515667746fd51a",
            "name": "Vehicle 1",
            "__v": 0
        },
        "__v": 0
    }
]

答案2

得分: 0

你需要使用 populate 方法来填充一个 vehicle 对象。

来自文档的示例:

rentSchema.
  findOne({}).
  populate('vehicle').
  exec(function (err, obj) {
    if (err) return handleError(err);
    console.log(obj);
  });

另外,在你当前的代码中,你还没有设置模型:

RentCollection = mongoose.model('RentCollection', rentSchema);

英文:

You will have to use the populate method to populate a vehicle object.

From docs:

rentSchema.
  findOne({}).
  populate('vehicle').
  exec(function (err, obj) {
    if (err) return handleError(err);
    console.log(obj);

  });

Also in your current code, you havent setted up model:

RentCollection = mongoose.model('RentCollection', rentSchema);

huangapple
  • 本文由 发表于 2020年1月3日 21:24:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579395.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定