Mongoose: CastError: Cast to ObjectId failed for value “[object Object]” at path “_id”

前端 未结 13 2088
再見小時候
再見小時候 2020-11-30 01:24

I am new to node.js, so I have a feeling that this will be something silly that I have overlooked, but I haven\'t been able to find an answer that fixes my problem. What I\'

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 02:04

    I've faced this error, That was because the value you want to filter in the _id field is not in an ID format, one "if" should solve your error.

    const mongoose = require('mongoose');
    
    console.log(mongoose.Types.ObjectId.isValid('53cb6b9b4f4ddef1ad47f943'));
    // true
    console.log(mongoose.Types.ObjectId.isValid('whatever'));
    // false
    

    To solve it, always validate if the criteria value for search is a valid ObjectId

    const criteria = {};
    criteria.$or = [];
    
    if(params.q) {
      if(mongoose.Types.ObjectId.isValid(params.id)) {
        criteria.$or.push({ _id: params.q })
      }
      criteria.$or.push({ name: { $regex: params.q, $options: 'i' }})
      criteria.$or.push({ email: { $regex: params.q, $options: 'i' }})
      criteria.$or.push({ password: { $regex: params.q, $options: 'i' }})
    }
    
    return UserModule.find(criteria).exec(() => {
      // do stuff
    })
    

提交回复
热议问题