Introduction to MongoDB and Mongoose

        MongoDB is definitely the most popular noSql database on the market now. This article will briefly explain the syntax and features of Mongoose and MongoDB.

Table of contents

What are MongoDB and Mongoose?

Link MongoDB database in Node

Define Mongoose's object schema schema

Addition, deletion, modification and query of MongoDB

        Find and create operations     

        update operation

        Delete operation


What are MongoDB and Mongoose?

        MongoDB is a relational model database, and their biggest advantage is that they can continue to use JSON objects without converting into database semantic thinking. MongoDB itself does not have object mode schema and model model , so for novices, developers also have more control and operation space. But more room to maneuver also means more opportunities to make mistakes.

        Mongoose is MongoDB's object modeling tool, which can help us create schema and model to reduce the chance of errors.

        

Link MongoDB database in Node

        First, please use this link and follow the instructions to download MongoDB: https://www.mongodb.com/try/download/community

        After the download is complete, you can also use the

        Second, we download mongoose using npm

npm install mongoose

         Introduce the module in the node file. After you download MongoDB, log in to the MongoDB atlas website and follow the instructions to find your database URL. Replace <username> and <password> in the URL with your username and password.

// 导入 mongoose 模块
const mongoose = require('mongoose');


// 你的mongodb的地址
const DB_URL = 'mongodb+srv://<username>:<password>@sandbox.o72ts.mongodb.net/?retryWrites=true&w=majority';

        Next, we use our database link to database link. The following settings will make your program use the new url parser, thus preventing you from using deprecated methods.

// 链接到数据库
mongoose.connect(DB_URL, {
	useNewUrlParser: true,
	useUnifiedTopology: true,
	useCreateIndex: true,
	useFindAndModify: false
})

Define Mongoose's object schema schema

        First, we usually create a new folder to hold all our schemas. But before we actually start creating our schema, let's take a look at the data types that common mongoose schemas can declare

const schema = new Schema(
{
  name: String, 字符串
  binary: Buffer, 2进制buffer
  living: Boolean, 布尔值

  date: Date, 日期

 用对象声明配置,type指数据类型,default默认值
  updated: { type: Date, default: Date.now },

数字类型的变量可以设置最大和最小值,required表示是否必填,接受布尔值
  age: { type: Number, min: 18, max: 65, required: true },

mixed表示任意类型都可以
  mixed: Schema.Types.Mixed,

数据库生成的唯一ID特定实例
  _someId: Schema.Types.ObjectId,


  array: [],数组
  ofString: [String], // 定义数组内的值的类型

嵌套声明
  nested: { stuff: { type: String, lowercase: true, trim: true } }
})

The only thing you may not be very familiar with here is ObjectId . ObjectId is a unique ID automatically generated by the database for the data when you insert data into the database. We usually use this unique value to operate on specific data. The ID is a class class. That is to say it is actually an object , but when you use the toSrting() method on the ObjectID, you can convert it to a 24-bit string. 

        From the above you may have found that if we use objects to define the data in the schema, we can not only define data types, but also add additional options . These include:

  • Default value: default
  • Built-in validators: such as min: 5 and max: 10
  • Is it required: required: true
  • Whether to convert the string to uppercase or lowercase, and remove spaces at both ends: lowercase: true, trim: true​​​​​​​​


        So next, let's actually create a user schema

const mongoose = require('mongoose')

const userSchema = new mongoose.Schema({
    name: String,
    age: Number,
    email: String,
    createdAt: Date,
    updateAt: Date,
    bestFriend: mongoose.SchemaTypes.ObjectId,
    hobbies: [String]
})

// 使用mongoose.model将schema定义给相关的集合
module.exports = mongoose.model('User', userSchema)

        After we define the schema, we first need to use mongoose.model() to define the schema to the collection in the related database . model() accepts two parameters, the first is the collection name, and the second is the schema value. After use, the schema we define will have an effect on the related collection.


Addition, deletion, modification and query of MongoDB

        Find and create operations     

        Now, we can create some user data that conforms to the format according to the schema format.

        According to an actual Express way of writing, registering a user usually uses a post request, and then we can obtain the data in the request body as the user's information.

// 由于数据库操作的异步的,我们需要使用异步async函数
router.post('/register', async (req, res) => {
    //用ES6对象解构的方式获得请求体数据
    const { name, email, password, age, hobbies } = req.body
})

        Then, we need to know whether the user already exists in the database, and if so, we need to inform the user that the mailbox is already in use. Then we need to use the query method. The most common query methods in MongoDB are find() , findOne() , and findById() . find will return all eligible data, but findOne and findById will only find the first eligible data. Their first parameter accepts a condition object, and the second parameter projection indicates the field of the returned data, which is equivalent to SQL's select. The third parameter is options, which we don't need for now.

        Because we don't want a mailbox to register an account repeatedly, we use the mailbox to search the database. If the user does not exist, we add a new user to the database, using create() or save ( ) .

router.post('/', async (req, res) => {
    const { name, email, password, age, hobbies } = req.body
    const signupAuth = await User.findOne({ email: email })
  
    // 使用try catch来进行错误处理
    try {
        if (signupAuth === null) {
            
                let result = await User.create({ name, email, password, age, hobbies })
                res.status(200).json(result)
           
        } else {
            res.json({ msg: 'this email is already used' })
        }
    } catch(err) {
        console.log(err)
    }
})

        update operation

        When we need to update a user's information, such as his username or password, we need to use the mongoDB update method. There is more than one way to update MongoDB, just like other operations, for example, in addition to save() , we can also use findOneAndUpdate(), the syntax of the two is as follows .

// 使用save方法,参数内必须有id值,不然将会被当做创建处理
COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

// update的第一个参数是查找条件,第二个参数为更改内容
const res = await CompletedSchema.updateOne(<condition>, <query>)

        For example, if we want to update the username of a related user, we need to first find the user as before, and then submit the updated information to the database.

router.patch('/updateuser', async (req, res) => {
    const { username, email } = req.body
    const user = await User.findOne({ email: email })
    try {
        // 如果你使用的是express的auth中间件,我们会在用户登录时,将其id存储在request的auth值中使用
        // 该值存储的属性名会根据中间件不同有差异
        // new: true配置会在数据更新后将其返回
        await User.findByIdAndUpdate(req.auth._id, updatedUser, { new: true })
    } catch(err) {
        res.json({ msg: 'error occured' })
    }
})

        delete operation

        The logic of the delete operation is very simple, and there is no essential difference from the update, but it has only one parameter, which is also used to confirm the conditions to find the data that needs to be deleted. Common methods are  deleteOne() and deleteMany().

const res = await CompletedSchema.deleteOne(<condition>)

        deleteMany() will delete all eligible data. In most cases, try to have deleteOne() to prevent accidental deletion. 

      Summarize:

       Database operations can be very complicated. This article is only an introductory teaching for MongoDB and mongoose. I hope you can perform simple database operations after reading this

Guess you like

Origin blog.csdn.net/a1611107035/article/details/127755931