Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

  • Print
  • + Share This
This chapter is from the book

MongoDB Models with Mongoose

To interact with MongoDB, you will be using the Mongoose ODM. It’s a light layer on top of the Mongo driver. To add the npm package, do this:

$ npm install --save mongoose

It’ll be good to keep this code modularized so your server.js file doesn’t get huge. Let’s add a db.js file with some of the base database connection logic:

var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/social', function () {
  console.log('mongodb connected')
})
module.exports = mongoose

You can get access to this mongoose instance by using the require function. Now let’s create a mongoose model to store the posts. Place this code in models/post.js:

var db = require('../db')
var Post = db.model('Post', {
  username: { type: String, required: true },
  body:     { type: String, required: true },
  date:     { type: Date, required: true, default: Date.now }
})
module.exports = Post

Now you have a model you can get with require. You can use it to interact with the database.

  • + Share This
  • 🔖 Save To Your Account