【node】------mongoose的基本使用------【凡尘】

1、安装mongoose

npm install mongoose

2、启动数据库

mongod --dbpath d:\data\db

3、引入mongoose模块并连接数据库

const mongoose = require("mongoose");

mongoose.connect("mongodb://127.0.0.1:27017/test1",function(err) {
     if(err){
         console.log('连接失败');
     }else{
         console.log("连接成功")
     }
});
 

 4、创建表以及字段类型

const User = mongoose.model("user",function(){
    name:String,
    age:Number
})

 5、增

const user = new User({
    name:"张三",
    age:19
})

user.save().then((result)=>{
    console.log("成功的回调")
},()=>{
    console.log("失败的回调")
})

 6、删

1、删除指定数据
User.remove({name:"zhao"}).then((result)=>{
    console.log(result)
})

result:是一个对象 返回值是受影响条数

2、删除所有数据 User.remove({}).then((result)=>{ console.log(result) })

//删除指定ID
3、User.findByIdAndRemove(id值).then((result)=>{

})

 7、改

User.update({name:"ya"},{$set:{name:"hua"}},{multi:true}).then((result)=>{
             console.log(result)
})

multi:true  表示修改多条数据

User.findByIdAndUpdate(id值,{$set:{需要修改的内容}}.then((result)=>{})

8、查

001查询符合条件的所有数据

User.find({name:ya}).then((result)=>{
    console.log(result)
})

result是查到的数据

 002、查询所有数据

User.find().then((result)=>{
             console.log(result)
})

 003、查询单条数据

User.findOne({name:"zhao"}).then((result)=>{
             console.log(result);
 })

 004、条件查询:

$lt(小于) $lte(小于等于) $gt(大于) $gte(大于等于) $ne(不等于);

User.find({"age":{"$lt":20}}).then((result)=>{
             console.log(result);
 })

User.find({"age":{"$lte":20}}).then((result)=>{
             console.log(result);
 })

 User.find({"age":{"$gt":20}}).then((result)=>{
             console.log(result)
})

User.find({"age":{"$gte":20}}).then((result)=>{
             console.log(result)
})

User.find({"age":{"$ne":19}}).then((result)=>{
             console.log(result)
})

 005、$in(包含 等于)  $nin(不包含 不等于)

User.find({"age":{"$in":[18,19]}}).then((result)=>{
             console.log(result)
 })

User.find({"age":{"$nin":[18,19]}}).then((result)=>{
             console.log(result)
})

 006、$or(或)

User.find({"$or":[{name:"zhao"},{age:20}]}).then((result)=>{
             console.log(result)
})

 007、$exists (判断当前关键字是否存在)

User.find({name:{"$exists":true}}).then((result)=>{
             console.log(result);
})

 008、查询指定列 如果不想要id值 只需要设置_id:0

User.find({},{name:1,age:1,_id:0}).then((result)=>{
             console.log(result);
})

 009、升序降序 sort()

User.find().sort({age:1}).then((result)=>{
             console.log(result)
})

 010、模糊查询 //

User.find({name:/a/}).then((result)=>{
             console.log(result)
})

User.find({name:/^z/}).then((result)=>{
             console.log(result);
})

User.find({name:/z$/}).then((result)=>{
             console.log(result);
})

 011、skip(n):查询n条以后的数据

User.find().skip(3).then((result)=>{
             console.log(result);
})

 012、显示n-m之间的数据 skip:跳过n条 limit 显示m-n条

User.find().skip(3).limit(2).then((result)=>{
             console.log(result)
})

猜你喜欢

转载自www.cnblogs.com/nanianqiming/p/9069760.html
今日推荐