i'm trying to get the _id
field of specific employee by req.body.name
:
const requestVacation = async (req, res) => {
try {
const employee = await Employee.find({ nameAR: req.body.name }).select('_id')
const vacation = new Vacation({
employeeId: employee._id,
type: req.body.type,
startDate: req.body.startDate,
endDate: req.body.endDate,
numberOfHours: req.body.numberOfHours,
});
await vacation.save();
res.status(200).json("vacation has been requested successfully");
} catch (err) {
console.log(err);
res.status(404).json(err);
}
};
the employee
variable will return this :
[ { _id: new ObjectId("630ba65261c73f3c8afc5c8c") } ]
but i only want the _id
value to save it as employeeId
in vacation collection, so how can i get the _id
value ?
i tried :
employee._id
but it returns undefined
i also tried :
const employee = await Employee.find({ nameAR: req.body.name }, { _id: 1 });
it returns the same result, how to get the _id
value out of it
CodePudding user response:
You are returning an array from the DB with find
. You can access the _id with employee[0]._id
or use findOne
, and it will return an object to be accessed with employee._id