Posts tagged:

mongoose model

The MEAN Stack: Mistakes You’re Probably Making With MongooseJS, And How To Fix Them

Jun 6 • Posted 1 year ago

This is a guest post from Valeri Karpov, a MongoDB Hacker and co-founder of the Ascot Project. _If you’re interesting in learning about how to use MongoDB with Node.js, sign up for a free, [introductory 7-week course on MongoDB and Node.js](https://education.10gen.com/courses/10gen/M101JS/2013_October/about)   For more MEAN Stack wisdom, check out his blog at TheCodeBarbarian.com.  Valeri originally coined the term MEAN Stack while writing for the MongoDB blog, and you can find that post here.

If you’re familiar with Ruby on Rails and are using MongoDB to build a NodeJS app, you might miss some slick ActiveRecord features, such as declarative validation. Diving into most of the basic tutorials out there, you’ll find that many basic web development tasks are more work than you like. For example, if we borrow the style of http://howtonode.org/express-mongodb, a route that pulls a document by its ID will look something like this:

app.get('/document/:id', function(req, res) { 
  db.collection('documents', function(error, collection) {
    collection.findOne({ _id : collection.db.bson_serializer.ObjectID.createFromHexString(req.params.id) },
        function(error, document) {
          if (error || !document) {
            res.render('error', {});
          } else {

            res.render('document', { document : document });
          }
        });
  });
});

Read more
blog comments powered by Disqus