Let's follow these steps to upgrade our Express /api/posts REST API to use Mongoose to read and write data from MongoDB:
- 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);
- 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 ...