node.js之mongodb操作

操作前需要安装sudo cnpm install mongoose

//加载mongoose模块
var mongoose = require("mongoose");
//连接mongodb-默认连接test数据库,可在地址后加上需要连接的数据库名字例:/myDb
var db = mongoose.connect("mongodb://localhost:27017/mydb");

db.connection.on("error",function(err){
    console.log("连接失败"+err)
})

db.connection.on("open",function(){
    console.log("连接成功")

})

//集合的数据模型定义,定义了字段名和字段的类型, 默认值
 var Schema = new mongoose.Schema({
     name:{type:String},
     age:{type:Number,default:0}
 },{
     collection:"test"//指定表
 })

//构造model对象用于操作数据,类似thinkphp实例化
 var model = db.model("test",Schema);

//创建添加数据(相当创建json) 需要把创建好的数据保存 这种方法是异步的
var testE = new model({
    name:"kkk",
    age:18
})
console.log(testE)
//把创建好的testE数据保存到mongodb数据库里面
testE.save(function(error,doc){
    if (error){
        console.log(error);
    }else{
       console.log("保存成功:"+doc);
   }
})

//创建添加数据 直接创建 无需保存 同步
model.create([{name:"a1"}],function(err,doc){
    if (err){
        console.log(err)
    }else{
        console.log(doc)
    }
})

//更改查找name为kkk,年龄age改为15 multi:updata默认是只改一条 multi:为true
model.update({name:"aaa"},{$set:{age:15}},{multi:true}, function (err) {
    if (err){
        return console.error(err);
    }
    console.log("更新成功");
});

//删除 删除name为kkk的数据
model.remove({name:"kkk"}, function (err) {
   if (err){
        console.log(err);
    }else{
        console.log("删除成功");
    }
})

//查询 查询name为aaa的数据
model.find({name:"aaa"}, function (err,doc) {
    console.log(doc);
})

//查询单条 //默认查询第一条
model.findOne({name:"qqq"}, function (err,doc) {
    console.log(doc);
});

//根据ID查找
model.findById("583541ce7a86530db8e5872e", function (err,doc) {
   console.log(doc);
})

//大于$gt
model.find({"age":{"$gt":9}}, function (err,doc) {
    console.log(doc);
});

//小于$lt 筛选age小于32
model.find({"age":{"$lt":32}}, function (err,doc) {

 console.log(doc);
 });

//不等于$ne 筛选age小于32
model.find({"age":{"$ne":0}}, function (err,doc) {
   console.log(doc);
});

//或者
model.find({"$or":[{name:"abc"},{age:0}]}, function (err,doc) {
    console.log(doc);
});

//判断某个字段是否存在来进行查询 $exists:false是不存在 true是存在
model.find({"name":{"$exists":true}}, function (err,doc) {
    console.log(doc);
})

//排序->sort
model.find({},null,{sort:{name:-1}}, function (err,doc) {
     console.log(doc);
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值