大家好,我在嘗試洗掉資料庫中的條目時收到此訊息。我在 req.body 上嘗試過 JSON.parse,在我的路由檔案中切換了路由,但似乎沒有任何效果。
這是我的控制器:
async function removeToy(req, res) {
try {
const { toyId } = req.params
const removedId = await toyService.remove(toyId)
res.send(removedId)
} catch (err) {
logger.error('Failed to remove toy', err)
res.status(500).send({ err: 'Failed to remove toy' })
}
}
這是服務:
async function remove(toyId) {
try {
const collection = await dbService.getCollection('toy')
await collection.deleteOne({ '_id': ObjectId(toyId)})
return toyId
} catch (err) {
logger.error(`cannot remove toy ${toyId}`, err)
throw err
}
}
還添加了 DB 外觀的圖片:

以及整個錯誤的圖片:

感謝任何形式的幫助!
uj5u.com熱心網友回復:
在您的資料庫中,您有一個 _id 型別為 的物件string。
在您的查詢中,您正在(可能)將 astring轉換為 a ObjectID,它是一個物件。您傳遞給的引數不僅ObjectId()不是它支持的東西(如錯誤所示,見下文),即使它是有效的,查詢也會導致 0 hits: 畢竟"TZ23c" !== ObjectId("TZ23c").
只需更改.deleteOne({_id: ObjectId(toyId)})為.deleteOne({_id: toyId}).
ObjectId()要么不帶引數(它將回傳一個新值),要么只需要 12 個位元組(24 個十六進制字符),例如:ObjectId("61e16f21f82a9db6a2094e78").
ObjectId 的字串表示 ( ObjectId().toString()) 不是任意字串:它是一個時間戳、一些標識哪個服務器生成它的值以及一些用于防止沖突的隨機值。并非每個字串都是有效的 ObjectId。
uj5u.com熱心網友回復:
由于訊息表明您傳遞給函式的 toyId 長度錯誤,它必須是 12 個位元組長,例如:
mongos> ObjectId("x448c")
2022-01-14T13:43:51.427 0100 E QUERY [js] Error: invalid object id: length
:
@(shell):1:1
mongos>
正確的是:
mongos> ObjectId("61e16facafe3aa6023c221bb")
ObjectId("61e16facafe3aa6023c221bb")
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/411363.html
標籤:
