How to do it...

Let's follow these steps to upgrade our Express /api/posts REST API to use Mongoose to read and write data from MongoDB:

  1. First, let's create a new Mongoose model called /models/posts.js. Separating our model definitions from our route configurations and middleware will make referencing models in multiple parts of our application much easier:
var mongoose = require('mongoose');var Schema = mongoose.Schema;var postSchema = new Schema({  title:  String,  content: String,  published: { type: Date, default: Date.now }});module.exports = mongoose.model('post', postSchema);
  1. Next, we'll replace our simple store array in /routes/api/posts.js to import and use our Mongoose posts model instead. We need to map our _id Mongoose model ID ...

Get MEAN Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.