-
Install mongoose
npm install mongoose
-
require mongoose in the
app.js
=>const mongoose = require("mongoose");
-
Connect to database with mongoose =>
mongoose.connect("mongodb://localhost/mongoose-example")
-
Create an overall schema =>
const Schema = new mongoose.Schema;
-
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; } } } });
-
Create a User model (model should be capitalized) =>
const User = new mongoose.model("User", userSchema);
-
Create User in db, then do sth. or catch error =>
User.create({ name: "Jane Doe", email: "[email protected]"}) .then() => { console.log("User successfully created!") } .catch(err => { console.log("Error at creation:", err); });
-
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));
-
Create another user with added object properties on userSchema =>
User .create({ name: "Creed Bratton", email: "[email protected]" }) .then( () => { console.log("User successfully created"); }) .catch(err => { console.log("Error at creation:", err); })
-
Check on mongodb compass if your created user is to be found in the
mongoose-example
database -
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" });
- 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} )
- 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`
- 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);