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

Time:05-25

I store value in db like this

PendingTasks: [

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

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

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

],

I make put request like this

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

From this request, I get the taskId through req.params.taskId and then search pending tasks and find the first object that matches this condition (notice there will be multiple tasks with the same Id), and then push this task to completed tasks and then delete this task from the pending task.

But I am not able to achieve it. When I search for a specific task through req.params.tasks, I get an empty array always.

Maybe because taskId is like this : 62863e2ed0d1bc5asas9b04711 whereas it is stored in DB like this ObjectId(62863e2ed0d1bc5asas9b04711)

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

How to solve this problem?

CodePudding user response:

ObjectID cannot be compared to a string.

You have to do:

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);

I ommited the ObjectId because it is not supported in the snippet, but ith should work the same since it is being converted to a 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);

  • Related