Skip to content

Instantly share code, notes, and snippets.

@1000miles
Last active September 6, 2019 13:35
Show Gist options
  • Save 1000miles/f84773ce7974b2538f5377fede14fc91 to your computer and use it in GitHub Desktop.
Save 1000miles/f84773ce7974b2538f5377fede14fc91 to your computer and use it in GitHub Desktop.

Mongoose Intro

  1. Install mongoose npm install mongoose

  2. require mongoose in the app.js => const mongoose = require("mongoose");

  3. Connect to database with mongoose => mongoose.connect("mongodb://localhost/mongoose-example")

  4. Create an overall schema => const Schema = new mongoose.Schema;

  5. Create a user schema with already instantiated Schema =>

    const userSchema = new mongoose.Schema({
       name: {
          type: String,
          minlength: 3,
          set: value => {
             return value
                .split(' ')
                .map(part => part[0].toUpperCase() + part.slice(1).toLowerCase())
                .join(" ");
          }
       },
       age: {
          type: Number,
          min: 18,
          max: 70
       },
       hobbies: [String],
       address: Object,
       role: {
          enum: ["user", "admin", "mod"],
          default: "user"
       }
       email: {
         type: String,
         required: true,
         unique: true,
         trim: true,
         validate: {
           message: "Email must be lowercase",
           validator: value => {
             if (value.toLowerCase() === value.toUpperCase()) return true;
             else return false;
           }
         }
       }
    });
  6. Create a User model (model should be capitalized) =>

    const User = new mongoose.model("User", userSchema);
  7. Create User in db, then do sth. or catch error =>

    User.create({ name: "Jane Doe", email: "janedoe@gmx.net"})
        .then() => {
          console.log("User successfully created!")
        }
        .catch(err => {
          console.log("Error at creation:", err);
        });
  8. Find User in db, then do something or catch error =>

    User.find( { name: "John Doe"} )
        .then(data => {
          // do something
          console.log("User found!");
        }
        .catch(err => console.log(err));
  9. Create another user with added object properties on userSchema =>

    User
       .create({
          name: "Creed Bratton",
          email: "creed@bratton.com"
       })
       .then( () => {
          console.log("User successfully created");
       })
       .catch(err => {
          console.log("Error at creation:", err);
       })
  10. Check on mongodb compass if your created user is to be found in the mongoose-example database

  11. List of query commands:

insertMany([]) to insert multiple documents
Place.insertMany([{ name: "Atrium Tower" }, { name: "Fernsehturm" }]);

.find({query}) returns all documents matching a query -> [{}, {}, ...]
Place.find().then(places => {
  console.log(places);
});

.findOne({query}) returns the first document matching a query {}
Place.findOne({ name: "Old Trafford" }).then(place => {
  console.log(place);
});

.findById(id) returns the document with the given id
Place.findById("5d722ca4f18a05aadc1f3276").then(place => {
  console.log(place);
});

Place.findOneAndDelete({ name: "Old Trafford" }).then(data => {
  console.log(data);
});

Place.deleteOne({ name: "123456" }).then(data => {
  console.log(data);
});

Place.deleteMany({}).then(data => {
  console.log(data);
});
Place.create({ name: "Old Trafford" });
  1. Connect to the mongo dabatase via shell/terminal
$ mongo # log into the database via shell/terminal
$ use mongoose-example  # switch to the database
$ db.users.find( {name: "Jane Doe"} ) # Syntax: db.collections.find( {query} )
  1. Drop the database
$ mongo # log into the database via shell/terminal
$ use mongo-example # switch to the database you want to delete
$ db.dropDatabase()
$ exit # to exit the mongo shell just type in `exit`
  1. Close database connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/databaseName');

mongoose.connection.close()
                   .then(console.log('Mongoose connection disconnected'))
                   .catch(err => console.log(`Connection could not be closed.`, err);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment