问题描述
这个问题发生在我身上,我试图在网上找到答案,但不幸的是找不到满足我要求的答案。 在这种情况下,我需要解决的问题,但我想有人可能会寻找相同的问题并发现它很难实现,在这里我公开我的解决方案,以防您想使用 Mongoose 删除数组元素,该数组元素应该是一个对象。 我知道我在网上找到了很多关于如何使用键和值对删除来匹配这些对象的信息,但在我的情况下,我不想以这种方式删除它们,我想使用索引方法来删除它们。
架构
const JobSchema = new mongoose.Schema({
date: {
type: Date,default: DateTime.local().toJSDate()
},jobs: {
type: []
},updatedAt: {
type: Date,default: DateTime.local().toJSDate()
}
})
数据
const data = [{"_id": "606764002a7a5d49a82de976","date": "2020-03-05T00:00:00Z","status": "worked","jobs": [ // the array of objects elements needed to be modified
{
"for": "VOW","paymentMethod": "time","from": "12:00","to": "20:00","totalTime": "08:00","rate": {
"normal": 10,"overtime": 10
},"payment": "102.85","jobDetails": {
"startedAt": "12:00","endedAt": "20:00","duration": "08:00"
},"description": "worked for Anthony brought back van from Southport"
},{
"for": null,"paymentMethod": "general","total": 102.34,"jobDetails": {
"startedAt": "09:00","endedAt": "12:00","duration": "03:00"
},"description": null
},{
"for": "Trueline","paymentMethod": "mile","rate": 1.5,"mileage": 100,"payment": 150,"jobDetails": {
"startedAt": "20:00","endedAt": "22:00","duration": "02:00"
},"description": null
}
]
}]
console.log(data)
我的解决方案
exports.deleteJob = asyncHandler(async (req,res) => {
try {
// receive the date_id and the object position in the array you want to delete
const { date_id,position } = req.body;
// find the job by its id
const job = await Mongoose
.model('Job',JobSchema,'name_of_your_mongo_collection')
.findById(date_id)
// set the specific field to null by capturing its position from client through 'position' variable
job.jobs[position] = null
// update with new data
await Mongoose.model('Job','jobs_' + req.user._id).findByIdAndUpdate(date_id,job)
// remove all null fields in the stated array
await Mongoose
.model('Job','jobs_' + req.user._id)
.updateOne(
{ _id: date_id },{ $pull: { jobs: null } }
)
// extract the job data again and send it to client
const updatedJob = await Mongoose.model('Job','name_of_your_mongo_collection').findById(date_id);
successResponse(updatedJob,200,res);
} catch (error) {
return errorHandler(error,res);
}});
注意:这对我自己来说并不是一个未解决的问题,因为我已经找到了上面的解决方案并且我的代码按预期工作,我认为它可以帮助其他人使用它或在线查找此信息以帮助他们适应我的解决他们未解决的问题。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)