微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Mongoose:如何使用索引删除数组元素

如何解决Mongoose:如何使用索引删除数组元素

这个问题发生在我身上,我试图在网上找到答案,但不幸的是找不到满足我要求的答案。 在这种情况下,我需要解决的问题,但我想有人可能会寻找相同的问题并发现它很难实现,在这里我公开我的解决方案,以防您想使用 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 举报,一经查实,本站将立刻删除。