[Summary]: Node.js operating MongoDB database - adding, deleting, modifying and checking


1. mongoose package

To operate the MongoDB database with Node.js, we can refer to the third-party package - mongoose
Chinese documentation: http://www.mongoosejs.net/

installation method:

npm i mongoose

2. Initialization steps

var mongoose = require('mongoose')
var Schema =  mongoose.Schema
//1.链接数据库
mongoose.connect('mongodb://localhost/itcast')

//2. 设计文档结构(表结构)
// 字段名称就是表结构中的属性名称
// 约束的目的是为了保证数据的完整性,不要有脏数据
var userSchema = new Schema({
    
    
    username:{
    
    
        type:String,
        required:true
    },
    password:{
    
    
        type:String,
        required:true
    },
    email:{
    
    
        type:String,
        required:true
    }
})

// 3. 将文档结构发布为模型
// mongoose.model 方法就是用来将一个架构发布为model
// 第一个参数:传入一个`大写名词单数`字符串用来表示你的数据库名称
//            mongoose会自动将大写名词的字符串生成 小写复数的集合
//            例如这里的 User 最终会变为users集合名称
// 第二个参数:架构Schema

//返回值:模型构造函数
var User = mongoose.model('User',userSchema)

Once we have the model constructor, we can use this constructor to do whatever we want with the data in the users collection!


3. CRUD operation

increase

var admin = new User({
    
    
    username:'admin2',
    password:'654321',
    email:'[email protected]'
})

admin.save((err,res) => {
    
    
    if(err) console.log("增加失败了");
    else console.log("增加成功了");
})

Res in save is the data you added

delete

//三、删
//1.根据条件删除所有:Model.remove(conditions,[options],[callback])
User.remove({
    
    
    username:'admin1'
},(err,res) => {
    
    
    if(err) console.log("删除失败");
    else console.log("删除成功,res是",res);
})
//2.根据条件删除一个:Model.findOneAndRemove(conditions,[options],[callback])
//3.根据id删除所有:Model.findByIdAndRemove(id,[options],[callback])

change

//1.根据条件更新所有:Model.update(conditions,doc,[options],[callback])
//2.根据条件更新一个:Model.findOneAndUpdate(conditions,[update],[callback])
//3.根据id更新一个:
User.findByIdAndUpdate("621d8ffa3d29f89e51103711",{
    
    
    password:'123'
},(err,res) => {
    
    
    if(err) console.log("更新失败");
    else console.log("更新成功");
})

check

//二、查
//1. 查集合中所有数据
User.find((err,res) => {
    
    
    if(err) console.log('失败了');
    else console.log(res);
})
//2. 根据Id查询
User.findById("621d8ffa3d29f89e51103711",()=>{
    
    
	if(err) console.log('失败了');
    else console.log(res);
})
//3. 其他条件查询
//User.find查询所有符合条件的数据,【返回一个数组包n个对象】
//User.findOne() 查询第一个符合条件的数据 【返回值是单个对象】
User.findOne({
    
    
    password:'654321'
},(err,res) => {
    
    
    if(err) console.log('失败了');
    else console.log(res);
})

Notice:

  • User.find queries all eligible data, [returns an array of n objects]
  • User.findOne() Query the first eligible data [the return value is a single object]

Guess you like

Origin blog.csdn.net/weixin_60297362/article/details/123211321