I want to return a single value from my model so I can compare it to the the current time in my middleware. Everything I'm finding in the mongoose docs is to return an array... how do I just get my value for key 'event_start' out of below:
const eventSchema = new Schema({
event_name: String,
venue_name: String,
address: String,
event_start: {
type: Date,
required: [true, 'Date & time of event start required']
},
event_end: {
type: Date,
required: [true, 'Date & time of event end required']
},
}
Here's what I have so far in my function. I'd like to find by id (can update below) since I have the event_id object stored in req.params:
module.exports.expiredEvent = (req, res, next) => {
const { id } = req.params;
const event = Event.find({ "_id": id })
How do I return the value for event_start from my db instead of an object?
CodePudding user response:
module.exports.expiredEvent = async (req, res, next) => {
const { id } = req.params;
const event = await Event.find({ "_id": id }, {_id: 0, event_start: 1});
console.log(event); // [{event_start: 2022-01-13T17:26:00.000Z}]
return event[0].event_start; // this will return 2022-01-13T17:26:00.000Z
}
CodePudding user response:
Since you're using mongoose, you should try findById
:
Event.findById(id, "event_start").exec();
Refer the document for more details.