I am trying to remove some json object from a result of mongoose findone function
but is not working
My code
export const transferGuest = async (req, res, next) => {
var guest = await Booking.findOne({"roomNumber": req.body.roomNumber, booked: true}).sort({createdAt: -1})
try{
const newBooking = new Booking(guest)
delete guest._id;
return res.status(200).json(guest)
}catch(error){
next(error)
}
}
but delete guest._id does not work.
How do I correct this?
CodePudding user response:
The findOne()
method returns a single document object so there's no need to call sort()
. If I understand your question well, you want to remove the _id
property from the result of the query. If that's the case, then you should try this:
export const transferGuest = async (req, res, next) => {
try{
var guest = await Booking.findOne({roomNumber: req.body.roomNumber, booked: req.body.booked}).select('-_id')
const newBooking = new Booking(guest)
return res.status(200).json(guest)
//return res.send(guest);
}catch(error){
next(error)
}
}
Note that you're not making use of newBooking
variable, you should remove it if you're not going to use it.
CodePudding user response:
You can't apply delete function on mongoose object first you need to change in plain object after you can apply delete function on it.
For convert into plain object you can use lean() mongoose function in your mongoose query
For refrence Change mongoose object into plain object
const guest = await Booking.findOne({roomNumber: req.body.roomNumber, booked: req.body.booked}).lean();
Try This:-
export const transferGuest = async (req, res, next) => {
var guest = await Booking.findOne({"roomNumber": req.body.roomNumber, booked: true}).lean();
try{
const newBooking = new Booking(guest)
delete guest._id;
return res.status(200).json(guest)
}catch(error){
next(error)
}
}