0

I have a schema called subcategory:

const subCategorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: false
    },
    category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category',
        required: true
    },
    image: {
        type: String,
        required: false
    }
})

However when executing this: const subCategoryRecord = await this.subCategoryModel.findById("idAsString") i get null

I read about other questions like this (says here that i should send new ObjectId('id') instead of string)

but i have another schema called category, and while doing findById by sending a string i DO get a result, what is the difference?

that's the category schema:

const categorySchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: false
    },
    image: {
        type: String,
        required: false
    }
})

this WORKS: const category = await this.categoryModel.findById('categoryIdAsString')

Two Horses
  • 1,401
  • 3
  • 14
  • 35

2 Answers2

0

Since you haven't specified the _id field in your Schema it will be of type ObjectId. For findById you can pass id as a String and Mongoose will convert it to ObjectId for querying.

Since you are getting a null response(no casting errors) I think you are passing a valid ObjectId string to the query and there might not be any record matching the provided id

You can use the below method to check if you are passing a valid id.

mongoose.isValidObjectId(idAsString)
vishnu
  • 1,961
  • 2
  • 7
  • 11
0

The _id is an object even if when tested with "type of" it will say it's a string. In my case this worked in the model :

authorId: { type: mongoose.Schema.Types.ObjectId, ref: "users" }

also if you ever need to compare an _id to and id saved as string you can use .equals() that will return a boolean :

user.userId.equals(checkUser._id)