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")
})
});
});
};