DEV Community

Margaret W.N
Margaret W.N

Posted on

Working With MongoDB

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');
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode
  • 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);
Enter fullscreen mode Exit fullscreen mode

End of day 3!

Oldest comments (0)