58 Operating mongoDB database in Node.js

Technical exchange QQ group: 1027579432, you are welcome to join!

Welcome to my WeChat public account: CurryCoder's program life

1. Database overview and environment construction

1.1 Why use a database
  • The data in the dynamic website is stored in the database.
  • Databases can be used to persist user information collected by clients through forms.
  • Database software itself can manage data more efficiently.
1.2 What is a database
  • A database is a warehouse that stores data, and can store data in an orderly and classified manner. It is language-independent software that can be manipulated through an API.
  • Common database software are: mysql, mongoDB, oracle, redis, etc.
1.3 mondoDB database download and installation
  • Download address: https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2012plus-4.2.8-signed.msi
  • mongoDB visual operation tool: Robo 3T 1.2.1
1.4 Database related concepts
  • A database software can contain multiple data warehouses, each data warehouse can contain multiple data sets, and each data set can contain multiple documents (specific data).
1.5 Mongoose third-party packages
  • Using Node.js to operate the mongoDB database needs to rely on the Node.js third-party package mongoose.
  • Use the npm install mongoose command to download and install
1.6 Start mongoDB
  • Run net start mongoDB in cmd to start mongoDB, otherwise mongoDB will not be able to connect. Run net stop mongoDB in cmd to shut down mongoDB.
1.7 Database connection
  • Use the connect method provided by mongoose to connect to the database.

    const mongoose = require("mongoose");
    
    mongoose
      .connect("mongodb://localhost/CurryCoder", {
        useNewUrlParser: true,
        useUnifiedTopology: true
      })
      .then(() => console.log("Database connection is successful!"))
      .catch(err => console.log(err, "Database connection failed!"));
    
1.8 Create a database
  • There is no need to explicitly create a database in mongoDB, if the database in use does not exist, mongoDB will create it automatically.

2. Add, delete, modify and query operations of mongoDB database

2.1 Create a collection
  • Creating a collection is a two-step process:
    • First, set the rules for the collection.
    • Then, create the collection. A collection is created by creating an instance of the mongoose.Schema constructor.
const mongoose = require("mongoose");
mongoose
  .connect("mongodb://localhost/course_demo", {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => console.log("Database connection succeeded"))
  .catch(err => console.log(err, "Database connection failed"));

// Set collection rules
const courseSchema = new mongoose.Schema({
  name: String,
  author: String,
  isPublished: Boolean
});

// Use rules to create collections
// Parameter 1: collection name, parameter 2: collection rule
const Course = mongoose.model("Course", courseSchema); // The collection name in the database is actually courses
2.2 Creating documents
  • Creating a document is actually inserting data into the collection. Divided into two steps:
    • First, create an instance of the collection;
    • Second, call the save() method under the instance object to save the data to the database.
  • Operations related to the database are asynchronous operations
// Creating Documents - Method 1
const course = new Course({
  name: "JavaScript",
  author: "CurryCoder",
  isPublished: true
});

course.save();

// Create document -- method 2
Course.create(
  {
    name: "Python",
    author: "Pink teacher",
    isPublished: true
  },
  (err, doc) => {
    // error object
    console.log(err);
    // the currently inserted document
    console.log(doc);
  }
);

// Create documentation -- method 2 supports syntax for asynchronous functions
Course.create({
  name: "C++",
  author: "sweeper",
  isPublished: false
})
  .then(doc => console.log(doc))
  .catch(err => console.log(err))
2.3 mongoDB database import data
  • Prerequisite: Find the installation directory of the mongodb database, and add the bin directory under the installation directory to the environment variables of the system.
  • Import data syntax: mongoimport -d database name -c collection name --file data file to be imported
    E:\Front-end development\JavaScript\practice code\mongoDB>mongoimport -d course_demo -c user --file
    ./user.json
    2020-07-02T21:16:45.454+0800    connected to: localhost
    2020-07-02T21:16:45.558+0800    imported 6 documents
    
2.4 Querying documents
  • Find documents based on conditions (if the condition is empty, find all documents)
    const mongoose = require("mongoose");
    mongoose
      .connect("mongodb://localhost/course_demo", {
        // The name of the course_demo database
        useNewUrlParser: true,
        useUnifiedTopology: true
      })
      .then(() => console.log("Database connection succeeded"))
      .catch(err => console.log(err, "Database connection failed"));
    
    // Set collection rules
    const userSchema = new mongoose.Schema({
      name: String,
      age: Number,
      email: String,
      password: String,
      hobbies: [String]
    });
    
    // Use rules to create collections
    // Parameter 1: collection name, parameter 2: collection rule
    const User = mongoose.model("User", userSchema); // The collection name in the database is actually users
    
    // Query all documents in the user collection
    User.find().then(result => console.log(result));
    
    // Find documents by constraints
    User.find({ _id: '5c09f267aeb04b22f8460968' }).then(result => console.log(result));
    
    // The findOne() method returns a document, by default it returns the first document in the current collection
    User.findOne({ name: 'Li Si' }).then(result => console.log(result));
    
    // match greater than less than
    User.find({ age: { $gt: 20, $lt: 50 } }).then(result => console.log(result));
    
    // match contains
    User.find({ hobbies: { $in: ['typing code'] } }).then(result => console.log(result));
    
    // Select the field name email to query, and do not want to query the field _id
    User.find().select('name email -_id').then(result => console.log(result));
    
    // Sort data in descending order by age -age
    User.find().select('age -_id').sort('-age').then(result => console.log(result));
    
    // skip how many pieces of data to skip limit limit the number of queries
    User.find().skip(2).limit(3).then(result => console.log(result));
    

Tags: Front-end

Posted by DKY on Tue, 31 May 2022 18:20:46 +0530