loading...

Working With MongoDB

mtee profile image Margaret W.N ・1 min read

Lets review some of the interesting concepts i've learnt today on mongodb and API'S.

  • Importing data.
    Asumming we have data in a dataJson.js file we can import this data to mongodb using mongo students < dataJson.js. Pretty easy!

  • Next on the list is mongoose!
    Mongoose is a data modelling library that handles all our database stuff for us so we don't have to deal with mongoDB directly ~Jonathan Mills. We need to install it first using npm install mongoose from the terminal then include it in our js file.

const mongoose = require('mongoose');

To set up a database connection we use the mongoose connect method which takes one parameter - the link to the local mongoDB database.

const db = mongoose.connect('mongodb://localhost/students');
  • Creating a Model. A model is essential when reading, retriving or manipulating data in a database. To create a model we define a new schema and pass in an object with all properties and their data types.
const mongoose = require('mongoose');

const {Schema} = mongoose;

const studentModel = new Schema(
  {
    firstName: { type: String},
    lastName: { type: String},
    major: { type: String},
  }
);

module.exports = mongoose.model('Student', studentModel);

End of day 3!

Posted on by:

mtee profile

Margaret W.N

@mtee

Developer | GADs 20 scholar | Diving into backend

Discussion

markdown guide