简体   繁体   中英

Return value from mongodb (not array) using mongoose

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?

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
}

Since you're using mongoose, you should try findById :

Event.findById(id, "event_start").exec();

Refer the document for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM