The following code does not work:
try {
const _id = req.params.id
await req.user.populate("tasks").execPopulate();
console.log("_id: ",_id)
console.log("_id type", typeof(_id))
//console.log(req.user.tasks);
const task = await req.user.tasks.find(o =>
o._id.toString() === _id)
updates.forEach((update) => task[update] = req.body[update])
await task.save();
Here is the console output:
_id: 5f1b5164acfd1a264d1589d5
src/routers/task.js:68
_id type string
src/routers/task.js:69
task: undefined
While if I change this line:
const task = await req.user.tasks.find(o =>
o._id.toString() === _id)
into this:
const task = await req.user.tasks.find(o =>
o._id.toString() === "5f1b5164acfd1a264d1589d5")
it works perfectly. Anyone know why?
Additional information: As asked in the comments, I looked at the exact characters in each string:
console.log(_id.split('').map(x => x.charCodeAt(0)))
/*
[
53, 102, 49, 98, 53, 49, 54, 52, 97, 99,
102, 100, 49, 97, 50, 54, 52, 100, 49, 53,
56, 57, 100, 53, 10
]
*/
console.log("5f1b5164acfd1a264d1589d5".split('').map(x => x.charCodeAt(0)))
/*
[
53, 102, 49, 98, 53, 49, 54, 52, 97, 99,
102, 100, 49, 97, 50, 54, 52, 100, 49, 53,
56, 57, 100, 53
]
*/
o._id.toString() === _id
doesn't work ando._id.toString() === "5f1b5164acfd1a264d1589d5"
does? Because with the output that you showed (and with the string coming from an URL path parameter, so there won't be any BOM or newline issues or such) both of them should have worked. Just a feeling - maybe you originally didn't have the.toString()
(because then it indeed wouldn't work becaueo._id
is anObjectId
and not a string)?_id.split('').map(x => x.charCodeAt(0))
and compare it to the same thing done with your string literal ("5f1b5164acfd1a264d1589d5".split('').map(x => x.charCodeAt(0))
).