user12361681
user12361681

Reputation: 107

Send nested object on GET

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

Upvotes: 0

Views: 77

Answers (2)

SuleymanSah
SuleymanSah

Reputation: 17858

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
    }
]

Upvotes: 1

Mobeen
Mobeen

Reputation: 985

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);

Upvotes: 0

Related Questions