How to use the isValidObjectId function from mongoose

Find comprehensive JavaScript mongoose.isValidObjectId code examples handpicked from public code repositorys.

mongoose.isValidObjectId is a function provided by Mongoose that checks whether a given value is a valid MongoDB ObjectId.

6
7
8
9
10
11
12
13
14
15
/**================ GET ONE USER ==================== */
async getUser({ params }, res) {
  try {
    const { usernameorid } = params;
    // Check if usernameoruserid is a valid ObjectId
    const isValidObjectId = mongoose.isValidObjectId(usernameorid);

    let user;
    if (isValidObjectId) {
      // Find user by id
fork icon5
star icon15
watch icon2

+ 2 other calls in file

17
18
19
20
21
22
23
24
25
26
27
28
29






//to check validation of objectId
const isValidObjectId = (objectId) => {
  return mongoose.isValidObjectId(objectId)
}


module.exports = {isValid,isValidObjectId,isValidRequestBody,isValidFiles}
fork icon0
star icon0
watch icon1

How does mongoose.isValidObjectId work?

mongoose.isValidObjectId is a function provided by the Mongoose library that takes in a value and checks whether it is a valid MongoDB ObjectId by performing a series of checks, including verifying the length and hexadecimal format of the value, and verifying that it can be converted to a MongoDB ObjectId instance. If the value passes all of the checks, the function returns true. Otherwise, it returns false, indicating that the value is not a valid MongoDB ObjectId. This function can be useful for validating user input or other data that is expected to represent MongoDB ObjectIds in a Mongoose application.

145
146
147
148
149
150
151
152
153
154
//         'Dữ liệu không được để trống!'))
// }

const { id } = req.params;
const condition = {
    _id: id && mongoose.isValidObjectId(id) ? id : null,
};

const [error, document] = await handlePromise(
    CongViec.findOneAndUpdate(condition, req.body, {
fork icon0
star icon0
watch icon0

8
9
10
11
12
13
14
15
16
17
      default:
        return false;
    }
  };
const isObjectIdValid = (id) => {
    return mongoose.isValidObjectId(id) && id.length === 24;
  };
  module.exports = {
    isvalidatGender,
    isObjectIdValid,
fork icon0
star icon0
watch icon0

Ai Example

1
2
3
4
5
6
7
const mongoose = require("mongoose");

const invalidId = "notanobjectid";
const validId = new mongoose.Types.ObjectId();

console.log(mongoose.isValidObjectId(invalidId)); // false
console.log(mongoose.isValidObjectId(validId)); // true

In this example, we use mongoose.isValidObjectId to check whether two values are valid MongoDB ObjectIds. The first value, 'notanobjectid', fails the checks and returns false, while the second value, a newly created MongoDB ObjectId instance, passes the checks and returns true. Note that in order to use mongoose.isValidObjectId, you need to have the Mongoose library installed and imported in your application.