Angular JS ObjectId to String

Angular JS

Binding fields in HTML form with Java script was a big and tedious logic we will normally write in jquery and Java script days. Angular js comes to rescue from writing lot of glueing and boiler plate coding in front end development.

Angular js is MVC client side framework which developed to ease life of front end developers.I have developed a few applications using angular js. In this blog post, I will share some issues I had faced and how I fixed.

ObjectId to string issue with mongodb

In my application, i use nodejs with angular js and mongodb as backend.

Everything is fine, models are getting stored in to db and able to update , delete etc. But problems come when i retrieve with where clause. For example, I store some reference as id in a collection. But when i fire a query with where clause, it is not returning.

The problem here is ObjectId and String type problems.

Whenever I save a model first time it is going to db as ObjectId type. but when i update the model and store it, it gets changed to ‘String’ type. here the problem arises.

When I run a find() with where clause , if it is ObjectId , there is not problems, but after some update in to model, it is saved as ‘String’, so it is not getting matched by the query.

I have written some logic to avoid this problem.

There are 2 ways you can fix this problem.

Before you read/find, you interrupt and convert the where condition value to ObjectID. Every read operation will be interrupted and the conversion happens before executing find against DB.
Interrupt the update/save operation of every model and convert the reference to ObjectId and save it.

I am going to the 2nd way as compare to read operations(there are much more find/reads) , the updates are less.

I will have the ‘Before save’ operation hooks in node js to interrupt the save operation of every model and do the conversion as follows:

module.exports = function (MyModel) {
var ObjectId = require('mongodb').ObjectId;
MyModel.observe('before save', function convertPersonIdToObjectId(ctx, next) {try {
if (ctx.instance) {
if (ctx.instance.personId) {
var comp_id = new ObjectId(ctx.instance.personId); // make an ObjectId
delete ctx.instance.personId;
ctx.instance.personId = comp_id;
}} else {
if ( {
var comp_id = new ObjectId(; // make an ObjectId
delete; = comp_id;}}
} catch (err) {
}  next();});};

-PersonId is the reference I store in my MyModel collection. now it is getting stored as ObjectId.

Leave a Reply

Your email address will not be published. Required fields are marked *