I am developing an application using Mongo, Node.JS and Angular Every time an object is delivered and processed in the interface, all objectId are converted to strings (this happens automatically when I send it as json), but when I save the objects back to mongo, I need to convert _id and any other references to other collections back to ObjectID objects. If I want to separate the database level well from the rest of my backend, it becomes even more messy, suggesting that my database level has the following signature:
database.getItem(itemId, callback)
I want my backend business to consider itemId as an opaque type (that is, it did not require a “mango” or knew nothing about ObjectId outside this database level), but at the same time I want to be able to take the result of this function and send it directly to the interface with the js expression.
exports.getItem = function(req, res) {
database.getItem(req.params.id, function(err, item) {
res.json(item);
});
};
Now I do the following:
exports.getItem = function(itemId, callback) {
if (typeof itemId == 'string') {
itemId = new ObjectID(itemId);
}
var query = {_id: itemId};
items.findOne(query, callback);
};
Thus, it can handle both calls that come from the backend, where the itemId link can come from another object and, therefore, can already be in the right binary format, as well as requests with itemId strings.
As I mentioned above, when I save an object that came from the front-end, and which contains many links to other collections, which are even more painful, since I need to go through the object and change all the id lines to ObjectIds.
All this is very wrong, there must be a better way to do this. What is it?
!