- 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
- Node.js SDK for MongoDB
- create schemas, use schema to access documents in DB
- asynchronous and uses promises
- 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
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
}
});
- 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 });
}