Connecting to MongoDB in MEAN Stack
Library and data model
Data model specifies what data is present in a document, and what data should be there in a document. For this we’ll be using Mongoose — a data modelling library that specifies environment and structure for the data. You can install Mongoose as a npm module through the command line.
npm install — save mongoose
Alright, since I started to get more serious with my garden project — so I chose to centralise our MEAN exercise around vegetables 🥦🥒
Setting connection file — app/models/vegetables
var mongoose = require(‘mongoose’);module.exports = mongoose.model(‘Vegetable’, { name : {type : String, default: ‘’} });
Create database connection configuration — config/db.js
module.exports = { url : ‘mongodb://localhost:27017/test’ }
Launch Robo 3t and create new database name “test”, new collection name “vegetables” :
Insert some data to this collection. Let’s pick Kale for now.
Project Structure
Run command to restart the server
npm start
You may use your favourite API testing tool (Postman, Insomnia etc) to access the same route.
Bonus track — my cucumber seedling.