Node connects to the database to implement addition, deletion, modification

First install the mongodb package

cnpm install mongodb

Import the mongodb package in the file

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017";
const db_name = "classWeb";

Connect to the database

MongoClient.connect(url, (err, client) => {
    
    
//连接db_name这个数据库并使用student这张表
const collection = client.db(db_name).collection('user');
    collection.find().toArray((err, result) => {
    
    
    console.log(result);
    client.close();
    })
})

Add a piece of data to the database table

 //新增数据
    var admin=new User({
    
    
        username:'admin',
        password:'123456'
    })

    admin.save(function (err,ret){
    
    
        if(err){
    
    
            console.log('插入失败');
        }
        else {
    
    
            console.log('插入成功');
            console.log(ret);
        }
    })

Delete a piece of data in the database

//删除数据
    User.remove(
    {
    
    
        username:'user2',
    },
    function (err,ret){
    
    
        if(err){
    
    
            console.log('删除失败');
        }
        else {
    
    
            console.log('删除成功');
            console.log(ret);
        }
    })

Modify a piece of data in the database

//修改数据
    User.updateMany(
        {
    
    
        username:'user1'
        },
        {
    
    
          $set:{
    
    "password":"10086"}
        },
        function (err,ret){
    
    
            if(err){
    
    
                console.log('修改失败');
            }
            else {
    
    
                console.log('修改成功');
                console.log(ret);
            }
        })

Query a piece of data in a database table

	//查询数据
	User.find(
	{
    
    
   	 username:'admin',
	},
	function (err,ret){
    
    
    	if(err){
    
    
       		 console.log('查询失败');
    	}
   		 else {
    
    
        	console.log('查询成功');
        	console.log(ret);
   		 }
	})

Basically, it is similar to mysql. Before reading this blog post, you can go to the rookie tutorial to learn the syntax of mongodb and type it on the command line, so that learning will be more convenient.

Guess you like

Origin blog.csdn.net/qq_43511063/article/details/108926844
Recommended