Skip to content

Latest commit

 

History

History
80 lines (73 loc) · 1.61 KB

File metadata and controls

80 lines (73 loc) · 1.61 KB

MongoDB and Mongoose

MongoDB

  • non relational, document-based DB
  • relatively easy to change schemas
  • data stored as JSON documents
    • no ORM (Object Relational Mapper) required
  • highly available and scalable

Mongoose

  • Node.js SDK for MongoDB
  • create schemas, use schema to access documents in DB
  • asynchronous and uses promises

Mongoose Schema

  • field definitions and collection name
const UserSchema = new mongoose.Schema({
    name: {
        ...
    },
    age: {
        ...
    },
}, { collection: 'users_list' }
);
  • type is required for each field
  • required field to make field mandatory
  • trim field to remove leading/trailing whitespace
  • validate field to check if field meets certain criteria

Mongoose Schema: Arrays

const UserSchema = new mongoose.Schema({
    name: {
        ...
    },
    age: {
        ...
    },
    hobbies: [String],
    default: [] // undefined field will default to empty array
});
  • Nested objects can be defined in schema
const UserSchema = new mongoose.Schema({
    name: {
        ...
    },
    age: {
        ...
    },
    address: {
        street: String,
        city: String,
        postalCode: String
    }
});

Mongoose Model

  • built from schema
  • class user
    • new User creates a document in memory
    • instance methods, static methods for CRUD
const User = mongoose.model('User', UserSchema); // class with reference to schema

function addUser(user) {
    const user = new User(user);
    const promise = user.save();
    return promise;
}

function findUserByName(name) {
    return User.find({ name: name });
}