In the previous post, I talk about what MongoDB is, what are the basic API. In this post, I am going to share some more details about the API to do CRUD operation (Create, Read, Update, Delete), and introduction to mongoose.js.
source
What Will I Learn?
- CRUD Operation with Mongo Console
- Introduction to mongoose (with MVC method)
Requirements
- MongoDB installed, and mongo shell start running
- Node.js installed
- NPM installed
- Understand JavaScript and basic MVC methadology
Difficulty
Intermediate
Tutorial Contents
Before reading through the tutorial, you need to setup mongodb and make sure mongodb is running.
Write Database Query with JavaScript
Some cool thing you can do with MongoDB is that you can write the Mongo Command in JavaScript and load it in the mongo console.
The reason is that MongoDB was build with C, C++ and JavaScript. So, JavaScript can be used to make query in MongoDB.
Example:
create these js
files.
userInfo1.js
db.users.insert({
name: {
firstName: "Johnson",
lastName: "Lai"
},
age: 22,
skills: ["javascript", "sql", "electronics"]
});
db.users.insert({
name: {
firstName: "Johnson 2",
lastName: "Lai 2"
},
age: 10,
skills: ["javascript", "sql", "machine learning", "electronics"]
});
userInfo2.js
var userArr = [
{
name: {
firstName: "Johnson",
lastName: "Lai"
},
age: 22,
skills: ["javascript", "sql", "electronics"]
},
{
name: {
firstName: "Johnson 2",
lastName: "Lai 2"
},
age: 10,
skills: ["javascript", "sql", "machine learning", "electronics"]
}
];
db.users.insert(userArr);
Both userInfo1.js
and userInfo2.js
can be loaded in mongo console.
In Mongo Console:
Change to a database with
use usersInfo;
Then, load that file with
load("c:/testfile/usersInfo1.js");
, the console should returntrue
to indicate that the file is loaded.The data will be inserted into database. To check it simply run
db.users.find().pretty()
CRUD Operation with MongoDB
Create
db.users.insert({name: "superoo7"});
### Read #### Get all data ``` db.users.find().pretty(); ```
Get data that match the specific value (Equal, $eq)
db.users.find({"name.firstName": "Johnson"}).pretty();
db.users.find({"age": {$eq:10}}).pretty();
$eq
in the command in mongo context means equal.
Get data with comparing data (Greater Than, $gt or Less Than, $lt)
db.users.find({"age": {$gt:9}}).pretty();
This query with $gt
are finding data with an age greater than 9.
Other operator
Greater than or equal ($gte)
db.users.find({"age": {$gte:10}}).pretty();
Less than or equal ($lte)
db.users.find({"age": {$lte:10}}).pretty();
Not Equal ($ne)
db.users.find({"age": {$ne:10}}).pretty();
In ($in)
Find value in an array, to check the existance of that value.
db.users.find({"skills": {$in: ["javascript"]}}).pretty();
Not in ($nin)
Return the value that are not in the array.
db.users.find({"skills": {$in: ["micro economy"]}}).pretty();
Exist
Return the value that exists
db.users.find({"skills": {$exists: true}}).pretty();
Update
For update operation, it takes in 2 objects, which is: the search object, and the update object. The query looks like this: db.users.update(<search term>, <update term>)
Update a data
db.users.update(
{"name.firstName": "Johnson"}, {$set: {"name.lastName": "Lai WH"} } );
Upsert
If the data does not exist, instead of update, it will create new one.
db.users.update(
{"name.firstName": "Johnny"}, {$set: {"name.lastName": "Depp"} }, {upsert: true} );
Update an array
Using $set
is important. Without it, the data will not update.
db.users.update(
{"name.firstName": "Johnson"}, {$set: {"skills.1": "HTML"} } );
This query will make ["javascript", "sql", "electronics"]
into ["javascript", "HTML", "electronics"]
Delete
Delete all that match
db.users.remove({"name.firstName": "Johnson"});
Delete One
db.users.remove({"name.firstName": "Johnson"}, 1);
Delete All
db.users.remove({});
Mongoose
Mongoose.js is a schema based solution to model your data in mongoDB. The schema creates key value pair for your data type
Get started
With Mongoose, Model-View-Controller can be practice.
The file structure can look like:
Folder
|- index.js
|- controller/
|- book.js
|- model/
|- book.js
Connect to the database with this method in the main index.js
file.
const mongoose = require('mongoose');
let dbLink = 'mongodb://localhost/dbName'
mongoose.connect(dbLink);
Create a schema to state how the data looks like.
In the model/book.js
file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let bookSchema = new Schema({
title: String,
keywords: Array,
published: Boolean
});
module.exports = mongoose.model('Book', bookSchema);
In the controller/book.js
file
const mongoose = require('mongoose');
const Book = require('../model/book');
let displayBook = () => {
// Find all book
Book.find({}, (err, books) => {
if(err) {
throw 'ERROR';
}
return;
}).then(data => {
console.log(data);
}).catch(err => console.log(err))
};
module.exports = displayBook;
in main file index.js
, simply just call the controller to get the data.
let displayBook = require('./controller/book');
displayBook();
Curriculum
That is all for me in this blog post. In the upcoming blog post, I will share some operation with mongoose, and making mongodb into production.
Posted on Utopian.io - Rewarding Open Source Contributors
Thank you for the contribution. It has been approved.
You can contact us on Discord.
[utopian-moderator]
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Hey @superoo7 I am @utopian-io. I have just upvoted you!
Achievements
Suggestions
Get Noticed!
Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!
Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations! This post has been upvoted from the communal account, @minnowsupport, by superoo7 from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.
If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
This post has received a 0.22 % upvote from @drotto thanks to: @banjo.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Nice post.
How would you compare MongoDB to Firebase Firestore? I am a long time MongoDB user but I am considering switching to Firestore due to the ease of setup and scaling. What do you think?
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Firebase is a database as a service (DaaS), so making an API is much faster. I used to use a lot of Firebase for prototyping with React as Front End. Is something you would like to use to get a prototype real fast but for production, you normally need to take control of all these by yourself, so Mongo and Node could be an API for it.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit