![](/img/trans.png)
[英]Add a new field to all documents of a collection with the value from the document field into MongoDB (Mongoose) with records of 300K+
[英]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.