34
loading...
This website collects cookies to deliver better user experience
----/
|
|--app.js
|--package.json
|--models
|--User.js
> npm init -y
> npm install mongoose nodemon
...
"start": "nodemon app.js"
...
User.js
, we'll create a Mongoose Model with the following lines of codeconst mongoose = require('mongoose');
const {Schema} = mongoose;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
name: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', userSchema);
CREATE DATABASE `transition-tutorial`;
USE `transition-tutorial`;
CREATE TABLE `users` (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
username VARCHAR(20) NOT NULL UNIQUE,
password VARCHAR(20) NOT NULL
);
id
property in our Schema. That's because MongoDB automatically assigns a 16-bit unique ObjectId to all documents in the model. Amazing.app.js
, write the following lines of codeconst mongoose = require('mongoose');
const User = require('./models/User');
(async () => {
try {
await mongoose.connect(
'mongodb://127.0.0.1:27017/transition-tutorial',
options);
} catch (err) {
console.log('Error connectiong to Database');
console.log(err);
}
});
We see from the connection that Mongoose is designed to work in an asynchronous environment. Mongoose supports both promises and callbacks.
The string 'mongodb://127.0.0.1:27017'
represents the connection URL for the mongoose instance. The URL in this tutorial is for those who have the MongoDB application installed on their local computer. Connecting to a cloud instance requires a connection string gotten from your MongoDB Cloud cluster homepage.
The 'transition-tutorial'
is the name of the database we will be querying. We did not create this database because MongoDB automatically creates it along with any defined Model when we connect and insert our first document using that Model Object. Another amazing reason to switch to MongoDB.
npm start
in the terminal.INSERT INTO `users` (name,username,password) VALUES ('John', 'johnsmith', 'p@$$w0rd!');
...
(async () => {
try {
const user = new User({name: 'John', username: 'johnsmith', password: 'p@$$w0rd!'});
await user.save();
console.log(user);
} catch (err) {
console.log(err);
}
})();
_id
property. This is the unique id that was generated by Mongoose;SELECT * FROM users
(async () => {
const users = await User.find({});
console.log(users);
});
find
method.const users = await User.find({name: 'John'});
const users = await User.find({}, 'name, username');
name
and username
properties, as well as the unique _id
. The SQL equivalent of this would look likeSELECT name, username FROM users;
const user = await User.findById(id);
console.log(user);
const user = await User.findOne({name: 'John'});
SELECT * FROM users WHERE name='John';
UPDATE TABLE users SET password='johnsmith001' WHERE name='John';
First, we could retrieve the data from the database, update the document and then save it again.
const user = await User.find({name: 'John'});
user.password = 'johnsmith001';
await user.save();
Secondly, we could findAndUpdate
, findOneAndUpdate
or updateOne
and the documents directly.
// Update multiple documents
const user = await User.findAndUpdate(
{},
{password: 'johnsmith001'},
{new: true}
);
// Update multiple documents with condition
const user = await User.findAndUpdate(
{name: 'John'},
{password: 'johnsmith001'},
{new: true}
);
// Update single document
const user = await User.findOneAndUpdate(
{name: 'John'},
{password: 'johnsmith001'},
{new: true}
);
// Update single document
const user = await User.updateOne(
{name: 'John'},
{password: 'johnsmith001'},
);
The first parameter to pass is an object of the conditions used to locate the required document, the second parameter is an object of the updates to be made to the document, and the {new: true}
tells mongoose to return the updated record. If this is not included, the old, outdated document will be returned instead.
DELETE FROM users WHERE name='John';
// Deleting collection of documents
const users = await User.deleteMany({name: 'John'});
const users = await User.remove({name: 'John'});
// returns {deletedCount: x} where x is the number of documents deleted.
// Deleting Single Document
const user = User.findOneAndDelete({name: 'John'});
console.log(user); // returns the deleted document
deleteMany
method is preferred over the remove
unless you have a good reason otherwise.populate
method.