通过 ObjectID 从对象数组中查找特定对象及其索引

Find a specific object and its Index from an Array of Objects through ObjectID

我这样在数据库中存储值

PendingTasks: [

{ uniqueId :1212322323
taskId : ObjectId(62863e2ed0d1bc5asas9b04711)
_id : 6289100e9823422047b7a},

{ uniqueId :1212322323
taskId : ObjectId(62863e2ed0d1bc5asas9b04711)
_id : 6289100e9823422047b7a},

{ uniqueId :1212322323
taskId : ObjectId(62863e2ed0d1bc5asas9b04341)
_id : 6289100e9823422047b7a},

],

我这样发出请求

router.put('/:companyId/:uniqueId/:taskId',........

从这个请求中,我通过req.params.taskId得到了taskId,然后搜索pending tasks,找到第一个符合这个条件的object(注意会有多个任务有相同的Id),然后push这个任务到已完成任务,然后从待处理任务中删除此任务。

但是我做不到。当我通过 req.params.tasks 搜索特定任务时,我总是得到一个空数组。

可能是因为 taskId 是这样的:62863e2ed0d1bc5asas9b04711 而它像这样存储在数据库中 ObjectId(62863e2ed0d1bc5asas9b04711)

const specificTasks= PendingTasks.findById(x => x.taskId === req.params.taskId)

如何解决这个问题?

ObjectID 无法与 string.

进行比较

你必须做的:

const specificTasks= PendingTasks.findById(x => x.taskId.toString() === req.params.taskId)
// Without mutation
const filt = PendingTasks.filter((elem, i) => i !== PendingTasks.findIndex((t) => t.taskId.toString() === '62863e2ed0d1bc5asas9b04711'));

// With mutation
PendingTasks.splice(PendingTasks.findIndex((t) => t.taskId.toString() === '62863e2ed0d1bc5asas9b04711'), 1);

我省略了 ObjectId,因为它在代码段中不受支持,但它应该可以正常工作,因为它正在转换为 string

const PendingTasks = [
  {
    uniqueId: 1212322323,
    taskId: '62863e2ed0d1bc5asas9b04711',
    _id: '6289100e9823422047b7a',
  },
  {
    uniqueId: 1212322323,
    taskId: '62863e2ed0d1bc5asas9b04711',
    _id: '6289100e9823422047b7a',
  },
  {
    uniqueId: 1212322323,
    taskId: '62863e2ed0d1bc5asas9b04341',
    _id: '6289100e9823422047b7a',
  },
];

const filt = PendingTasks.filter((elem, i) => i !== PendingTasks.findIndex((t) => t.taskId.toString() === '62863e2ed0d1bc5asas9b04711'));
console.log('filt: ', filt);

PendingTasks.splice(PendingTasks.findIndex((t) => t.taskId.toString() === '62863e2ed0d1bc5asas9b04711'), 1);
console.log('PendingTasks: ', PendingTasks);