Home >Web Front-end >JS Tutorial >Teach you step by step how to use Node to connect to mongodb

Teach you step by step how to use Node to connect to mongodb

青灯夜游
青灯夜游forward
2023-04-04 19:36:502002browse

Teach you step by step how to use Node to connect to mongodb

To use Node.js to connect to MongoDB, you usually use the Mongoose Object Document Model (ODM) library. Let’s briefly introduce how to use Mongoose to connect to MongoDB.

Mongoose is a Node.js package that provides an interface for using the mongo database. It is a very lightweight npm package for use in applications. Mongoose has all the set of methods to connect and access data stored in a Mongo database.

react-giant: A react next.js mongodb learning project.

Install the Mongoose library

This is one of the necessary steps for Node.js project development. Use the npm command to install it. Enter the following command in the terminal to install:

npm install mongoose --save

Connecting to MongoDB

Usually when using a database, you need to establish a connection first. The connection is established in the following ways:

const mongoose = require("mongoose");

const connectDb = async () => {
    await mongoose.connect("mongodb://localhost:27017/admin");
};

connectDb();

In the above code , the mongoose.connect() function is used to establish a connection to MongoDB. The first parameter specifies the MongoDB connection URL, in the format mongodb://f7e6dec31ab1a0471d06c55afaca8d77:298c9bd6ad6e8c821dc63aa0473d6209/6a1c441b3cb87988672d89ab255c6360?a436f88d8f7c0913a3ddc875cb14d4fa, where &lt ;host> Specify the host name or IP address where MongoDB is located, 298c9bd6ad6e8c821dc63aa0473d6209Specify the port number of MongoDB, 6a1c441b3cb87988672d89ab255c6360 Specify the database to be connected The name, a436f88d8f7c0913a3ddc875cb14d4fa is some configuration items, passed as parameters, such as ?useNewUrlParser=true&useUnifiedTopology=true. For databases that require username and password to connect, the f7e6dec31ab1a0471d06c55afaca8d77 parameter method is username:password@127.0.0.1:27017. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]

It should be noted that there are some differences in the connection methods of different versions of mongoose. The above code is It can be used normally in version 7.0.2.

Define models and schemas

When using Mongoose, you usually need to define a model and corresponding schema first. A model refers to a collection in MongoDB, and a schema specifies the structure and fields of each document in the collection. The following is a simple schema definition example:

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
        unique: true,
        maxlength: [255, "Email length must be at most 255"],
    },
    ip: {
        type: String,
        required: true,
    },
});

const User = mongoose.model("User", userSchema);

CRUD operations

After defining the model and schema, you can use the model to perform CRUD (create, read, update, delete) operations. The following are some commonly used sample codes:

const mongoose = require("mongoose");

// 创建记录
async function createUsers() {
    const result = await User.create({
        username: "Quintion",
        email: "quintiontang@gmail.com",
        ip: "127.0.0.1",
    });
    return result;
}

// 查询文档列表
async function getUsers() {
    const users = await User.find();
    return users;
}

// 查询单个
async function getUser() {
    const user = await User.find({
        username: "Quintion",
    });
    return user;
}
// 删除记录
async function deleteUser() {
    return await User.remove({
        username: "Quintion",
    });
}

The above code is just a simple example. If you need a complete runnable code, you can check out the following project:

react- giant: A react next.js mongodb learning project.

For more node-related knowledge, please visit: nodejs tutorial!

The above is the detailed content of Teach you step by step how to use Node to connect to mongodb. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete