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