[SOLVED]Checking if input is an ObjectId in Mongo

[SOLVED]Checking if input is an ObjectId in Mongo
0

#1

I’m trying to check if the id entered is an Objectid. I’ve tried checking by length, if it’s a string and several other methods from the Mongo docs. Any suggestions to point me in the right direction would be helpful.

  app.route('/api/books/:id')
   .get(function (req, res){
   var bookid = req.params.id;//expect(bookid).to.have.lengthOf(24); 
   var id = new ObjectId(bookid); //Must convert to mongo object id to search by it in db
   
    //if(bookid.length < 24){res.json('Book doesn't exist")}else{code below goes in here}
    MongoClient.connect(MONGODB_CONNECTION_STRING, function(err, db) {    
      var collection = db.collection('books');
      collection.find({_id:id}).toArray(function(err, result) {
      //check if there's records in database to display
      if(result.length !== 0) {
        res.json(result[0]);
      } else {
        res.json("No record exist");       
      }
    });
  });
 }) 

.post(function(req, res){
  var bookid = req.params.id;
  var usercomment = req.body.comment;
  var id = new ObjectId(bookid);

  MongoClient.connect(MONGODB_CONNECTION_STRING, function(err, db) {
  var collection = db.collection('books')
    collection.findAndModify({_id:id}, function(err, doc){       
    collection.update({_id: id},{ $push:{comments: usercomment}})
      res.json(id + " has been updated")
     })
    });
  })                  

    .delete(function(req, res){
  var bookid = req.params.id;
  var id = new ObjectId(bookid);
  //if successful response will be 'delete successful'
 MongoClient.connect(MONGODB_CONNECTION_STRING, function(err, db) {
  var collection = db.collection('books')
  collection.findOneAndDelete({_id: id}, function(err, doc){
    res.send("delete successful")
  })
});
});
};

#2

mongoose.Types.ObjectId.isValid()


#3

Why aren’t you using mongoose? It has ObjectId method .isValid().

Also it manages mongo connections so you don’t have to do it yourself.


#4

I’m working on a beta project, which they give you a boilerplate. They’re not using mongoose. Using Mongo native drivers instead of mongoose.


#5

Can’t you just add mongoose to dependencies and use mongoose validator?


#6

There’s a few npm modules that do this, also. The boilerplate is using mongo native drivers.


#7

It seems mongo also has isValid function now.
https://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html


#8

I tried:
Unless I have syntax wrong.
if(bookid.isValid() === false){
res.json(“error”)
}


#9

I’d say

ObjectID.isValid(bookid)

Don’t forget to require:

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

#10

Thank you, will try that now


#11

Did you read what is in the link? You should write

var ObjectID = require('mongodb').ObjectID;
ObjectID.isValid('object id');

#12

Yes, if you want to look at project it’s at https://glitch.com/edit/#!/free-timpani?path=routes/api.js:74:91


#13

I figured it out. I used isValid, like prohorva and jenovs suggested. Calling a new ObjectId wasn’t neccessary. Instead of the variable to contain the ObjectId, var id = new ObjectId(bookid), I used ObjectId('bookid') in the find and update method.

.post(function(req, res){
      var bookid = req.body.id;
      var usercomment = req.body.comment;
      //var id = new ObjectId(bookid);
      
     //console.log(ObjectId.isValid(bookid))
      if(!ObjectId.isValid(bookid)){res.json("No record exist")}
      else{
       MongoClient.connect(MONGODB_CONNECTION_STRING, function(err, db) {
        var collection = db.collection('books')
        var id = new ObjectId(bookid);
          collection.findAndModify({_id:id}, function(err, doc){       
          collection.update({_id: id},{ $push:{comments: usercomment}})
          res.json(bookid + " has been updated")
      })
    });
     }