I am currently trying to set up a backend API with mongo and express, and i am struggling to get a create route to work. This is my route:
reservationsRouter.post("/", (req, res) => {
assert.notEqual(req.body.user, null);
const user = User.findById(req.body.user);
const reservation = new Reservation({
dateStart: req.body.dateStart,
dateEnd: req.body.dateEnd,
user: user
});
res.json(reservation);
reservation.save();
});
My reservationSchema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ReservationSchema = Schema({
user: { type: Schema.ObjectId, ref: "User", required: true },
dateStart: { type: String, required: true },
dateEnd: { type: String, required: true }
});
module.exports = ReservationSchema;
and my userSchema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = Schema({
_id: { type: String, required: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
reservations: [{ type: Schema.Types.ObjectId, ref: "Reservation" }]
});
module.exports = userSchema;
My problem is, that when i save a reservation and GET all the reservations, it does not have a user
attribute, even though i have specified it in the schema:
{
"dateStart": "1234",
"dateEnd": "12345",
"_id": "5b127d9d3d8256eedd31173b"
}
EDIT: I have rewritten the route as follows so that the callback returns the reservation with the user, but still, when i GET all the reservations, the User is not included as in the example above.
reservationsRouter.post("/", (req, res) => {
assert.notEqual(req.body.user, null);
const user = User.findById(req.body.user, (err, user) => {
if (err) res.send(err);
else {
const reservation = new Reservation({
dateStart: req.body.dateStart,
dateEnd: req.body.dateEnd,
user: user
});
res.json(reservation);
reservation.save();
}
});
});
You might want to check out the entire repo: https://github.com/SchulenbergOrg/backend/tree/mongo