簡體   English   中英

ZCCADCDEDB567ABAE643E15DCF0974E503Z:如何使用今天的日期作為字段值更新集合中的所有文檔

[英]Mongoose : How to update all documents in a collection with todays date as field value

我有一個名為“dueDate”字段的集合,來自前端的 function 定期發送當前日期。 該日期數據用作更新的標准。 不幸的是,當我運行 function 時,我得到一個空數組。

這是 controller:

exports.UpdateComplainStatus = asyncHandler(async (req, res, next) => {
  const { date } = req.params;

  Employee.updateMany(
    { dueDate: new ISODate(date) },
    { $set: { complainStatus: 'good' } }
  ).exec((err, pool) => {
    if (err) {
      console.log(err);
    } else {
      console. log('due date updated successfully...');
      res.send(pool);
    }
  });
});


這是架構;

const mongoose= require('mongoose');
const EmployeeSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
complainStatus:{
  type:String,
  required:false,
  default:'good'
},
complainDetail:{
  type:String,
  required:false,
},


dueDate:{
  type:Date,
  required:false,

},
  attendances: {}
    
   
},{timestamps:true});

const Employee=mongoose.model("Employee", EmployeeSchema,'employee001');

module.exports=Employee


這是我想要實現的目標: 1.Filter only document with endDate: "with today's date" 2.Update 投訴狀態字段(例如從暫停到良好)

我不認為Mongoose exec function 將回調作為參數。 你應該試試這個:

exports.UpdateComplainStatus = asyncHandler(async (req, res, next) => {
  const { date } = req.params;
  try {
   const response = await Employee.updateMany(
    { dueDate: new ISODate(date) },
    { $set: { complainStatus: 'good' } }
   ).exec();
   console.log(response); <-- This won't be an array of updated documents. 
   const updatedDocs = await Employee.find(
    { dueDate: new ISODate(date) }
   ).exec();
   res.send(updatedDocs);
  } catch (err) {
    console.log(err);
  }
});

文檔中所述, updateMany將返回匹配、更新等對象的計數。 將更新的文檔本身作為 API 響應返回。 您將不得不使用find再次獲取它們。

暫無
暫無

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

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