Git Product home page Git Product logo

mongooseactivities's Introduction

Welcome to a Guide for Mongoose

mongoose

Mongoose VS. MongoDB

  • Brief introductions tot he differences between Mongoose and MongoDB.
  • Brief examples and installation procedure.
  • (Using Mongo Shell)

Mongoose

  • Mongoose is a popular npm package.
  • Known as the ODM (Object Document Mapper. A code library that converts the transfer of data stored in database tables into objects.
  • Mongoose gives us the power to organize our database by using schemas.
  • Allows you to define objects with a schema that is mapped to a MongoDB document.
  • Once a schema is defined, then you can create a model based on a specific schema.
  • Once you have defined your schemas and models, Mongoose contains several functions that allow you to validate, save, delete, and query your data using similar MongoDb functions.

MongoDB

  • MongoDb is a database that stores your data as documents. (JSON Structure).
  • The documents are then saved to collections.
  • Scalable and consistent
  • Uses the Mongo Shell
  • MongoDB has a flexible data model, making it easier to change data within your application
  • Layout:
{
  dogBreed: "Sheperd",
  dogName: "Max"
}

Creating a MongoDb/Mongoose Database

  • A Quick Tutorial

Setting up Mongo

Setting up Mongoose

  • Make a new directory for your Mongoose code
  • npm init
  • Install mongoose and mongoose.connect
  • $ npm install mongoose --save
  • Connect to the MongoDB database. For example, i've opened a connection to a databse that i've called 'mongoose-notes' using the connect function.
  • Insert into index.js file:
const mongoose = require('mongoose)
mongoose.connect('mongodb://localhost/mongoose-notes');
  • The connect function takes in two other optional parameters.
  • You can use this for example:
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mongoose_notes', function (err) {

   if (err) throw err;

   console.log('Successfully connected');

});
  • If an error occurs when connecting to your database, the error is thrown and all further proccesses are stopped.

Defining a Mongoose Schema

  • In the mongoDb layout, i've converted the document into a mongoose schema:
const dogSchema = mongoose.Schema({
    dogBreed: String,
    dogName: String
});
  • This is a very basic schema that contains two properties with no attributes associated with it.
  • You can convert the Breed and firstName properties to be child objects of a name property.
const dogSchema = mongoose.Schema({
    name: {
        dogBreed: String,
    dogName: String
    },
    created: Date
});
  • Mongoose allows you to create flexible schemas with many different possible combinations of how you can organize your data.
const dogSchema = mongoose.Schema({
    name: {
        dogBreed: String,
    dogName: String
    },
    Description: String,
    Coloring: String,
    Toy: String,
    Created: {
        type: Date,
        default: Date.now
    }
});
  • Above I have added several strings to the schema, as well as a current date.

Creating and Saving Mongoose Models

  • Continuting the Breed and dogName schema:
const Name = mongoose.model('Name', nameSchema);
  • A Mongoose Model, when saved, created a document in the MongoDB with the properties defined by the schema it's derived from.
  • To demonstrate creating and saving an object, in the next example, I am going to create several objects.
const shepherdName = new Name {
    _id: new mongoose.Types.ObjectId(),
    name: {
        dogBreed: 'Shepherd',
        dogName: 'Max',
    },
    Description: 'timid, quiet, friendly',
    Coloring: 'Brown and grey',
    Toy: 'plush toy duck'
};

shepherdName.save(function(err){
    iff(err) throw err;

    console.log('Dog Breed Successfuly Saved')
});
  • The example starts by creating and saving a shepherdObject thats breated from the Name model.
  • Inside the save function of the ShepherdObject, if an error occurs, the application will output an ecxeption.
  • When the save is successful, inside the save function, the new objects will be saved.

Create your Seeder file

  • In order to view the collection from your schema in your Mongo Shell, you will need a seeder file
const mongoose = require('mongoose');
const Shepherd = require('../model')

mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost:27017/people", { useNewUrlParser: true, useUnifiedTopology: true  }, {versionKey: false});

let db = mongoose.connection;

db.once("open", () => console.log('connected'));

Dog.deleteMany({}).then(() => console.log('deleted'))


const dog = new Shepherd ({
    dogBreed: 'Shepherd',
    dogName: 'Max',
    Description: 'timid, quiet, friendly',
    Coloring: 'Brown and grey',
    Toy: 'plush toy duck'
  });

  human.save().then(saved => console.log(saved));

// How long to wait until the database closes, closes connection
  setTimeout(() => {

    db.close();

  },
2000
  ) 

.... not finished

mongooseactivities's People

Contributors

lillianparis avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.