Nehal Ahmad
Nehal Ahmad

Reputation: 57

Why findOne({ id }) is not working properly in mongoose 6.012

I am using mongoose to find one user by its id but it is not working correctly. I tried several different approaches but only got the wrong results or errors.

Here is my code.

const { id } = req.params;
const user = await User.findOne({ id });
console.log(id);
console.log(user);
return res.redirect("back");

I tried following approaches

1 - await User.findOne({ id }); returning first user no matter what is id.

target id: a8fc083f3f55494fa2cadf9
{
  _id: new ObjectId("618fb03e37876d1f0bccb945"),
  name: 'bohetefyhy',
  email: '[email protected]',
  dataRealm: new ObjectId("618fb0119eefb1308fe65610"),
  role: 'user',
  createdAt: 2021-11-13T12:31:58.846Z,
  updatedAt: 2021-11-15T08:03:34.422Z,
  __v: 0
}

2 - await User.findOne({ id: id }); returning same result as above (1).

3 - await User.findOne({ _id: id }); giving error.

CastError: Cast to ObjectId failed for value "a8fc083f3f55494fa2cadf9" (type string) at path "_id" for model "User"
at model.Query.exec (C:\Users\khan\Documents\Projects\030FL014_Windshield\app\node_modules\mongoose\lib\query.js:4545:21)
at model.Query.Query.then (C:\Users\khan\Documents\Projects\030FL014_Windshield\app\node_modules\mongoose\lib\query.js:4644:15)
at processTicksAndRejections (internal/process/task_queues.js:97:5)

I also noticed that in the result there is a missing id field that mongoose adds. And for _id value is new ObjectId("618fb03e37876d1f0bccb945") instade of simply "618fb03e37876d1f0bccb945"

I am using

"mongoose": "^6.0.12",

MongoDB 5.0.3 2008R2Plus SSL (64 bit)

Ok, so I found the issue, there are only 23 characters in my object Id one is missing from start. but still why there is id field missing that mongoose add and why there _id is new ObjectId("618fb03e37876d1f0bccb945") instead of simply "618fb03e37876d1f0bccb945" when I'm logging

Upvotes: 3

Views: 8126

Answers (9)

Youssouf Oumar
Youssouf Oumar

Reputation: 45865

If you are querying by ID, use findById instead of findOne as the documentation suggests:

const user = await User.findById(mongoose.Types.ObjectId(id));

Upvotes: 0

mrgreen
mrgreen

Reputation: 73

I faced the same types of problem today and solved it by community guideline.

I Solved it with these simple code. Maybe you can try it too. Here I tried it with Email, you can try it with _id. I found both of them valid.

const router = require('express').Router();
const userModel = require('../models/usermodel');

    router.post('/api/user/registration', async (req, res) => {
    const emailX = req.body.email;
    const emailExist = await userModel.findOne({'email': emailX }); // Finding the Email exist or not
    console.log(emailX, "Email Exist: =>", emailExist);
})

Upvotes: 1

Tamal Mallick
Tamal Mallick

Reputation: 99

I hope it will be work

const { id } = req.params;
const user = await User.findById({ _id: id });

Upvotes: 0

Sleepingisimportant
Sleepingisimportant

Reputation: 1112

I use mongodb version v6.0.0, and this works for me.

const User = mongoose.model("User", userSchema); 

const userID="123123123123";

User.findOne({ _id: userID }, function (err, foundItem) { 
      console.log("foundItem: "+foundItem);
    }

userID type: String

Upvotes: 1

Irshad ali
Irshad ali

Reputation: 1

You can start debugging the issue by adding the following piece of code and try to check if the mongoose query is passing all the parameters which you passed:

mongoose.set('debug', true);

I also faced similar issue and I was able to resolve it by updating the schema with _id like below:

_id:  mongoose.Types.ObjectId

Upvotes: 0

Kiran Kumawat
Kiran Kumawat

Reputation: 1

Try this I hope this will work:

const {id} = req.params

await User.findOne({_id: ObjectId(id)})

Upvotes: 0

Ibrahim
Ibrahim

Reputation: 51

I was facing the same problem, and this is how I solved to get the data for the Id I'm looking for.

const ObjectId = require('mongodb').ObjectId;

const id = '61929f3efc232d63cd9dcb6b';

user.findOne({ _id: ObjectId(id) })
.then((result) => {
 console.log(result);
})
.catch((err) => {
 console.log(err);
});

This is the data that I have for users information

Users information data

The Output:

{
  _id: new ObjectId("61929f3efc232d63cd9dcb6b"),
  name: 'Ibrahem',
  email: '[email protected]',
  age: 24,
  createdAt: 2021-11-15T17:56:14.089Z,
  updatedAt: 2021-11-15T17:56:14.089Z,
  __v: 0
}

Upvotes: 2

Elzohary
Elzohary

Reputation: 512

try:

await User.findOne({ _id: mongoose.Types.ObjectId(id) });

Upvotes: 0

DevRobert
DevRobert

Reputation: 1

Mongoose's findById method casts the id parameter to the type of the model's _id field so that it can properly query for the matching doc.

Try also checking

if (id.match(/^[0-9a-fA-F]{24}$/)) {
  // Yes, it's a valid ObjectId, proceed with `findById` call.
}

OR

var mongoose = require('mongoose');
mongoose.Types.ObjectId.isValid('your id here');

Upvotes: 0

Related Questions