簡體   English   中英

使用 mongoose 從 mongodb(非數組)返回值

[英]Return value from mongodb (not array) using mongoose

我想從 model 返回單個值,以便將其與中間件中的當前時間進行比較。 我在 mongoose 文檔中找到的所有內容都是返回一個數組......我如何才能從下面獲取鍵“event_start”的值:

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']
  },
}

這是我到目前為止在 function 中的內容。 我想按 id 查找(可以在下面更新),因為我在 req.params 中存儲了 event_id object:

module.exports.expiredEvent = (req, res, next) => { 
   const { id } = req.params;
   const event = Event.find({ "_id": id })

如何從我的數據庫而不是 object 返回 event_start 的值?

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
}

由於您使用的是 mongoose,您應該嘗試findById

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

有關詳細信息,請參閱文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM