使用mongoose、nodejs连接MongoDB数据库

//npm安装依赖包后、导入mongoose
var mongoose = require('mongoose');
//连接本地的mongodb数据库stu
mongoose.connect('mongodb://127.0.0.1:27017/stu');
var db = mongoose.connection
db.on('error',function(){
    console.log("数据库连接出错")
})

//生成一个Schema,相当于student集合的一个映射,里面定义字段名和类型,并关联对应的集合student
let stuSchema = mongoose.Schema({
	name: String,
	age: Number
},{collection:'student'})

//根据Schema生成一个model,model就是对数据库增删改查的对象,model里面提供了很多方法来对数据库进行操作
let stuModel = mongoose.model('stu',stuSchema)

//插入语句,需要对定义的字段赋值来构造一个model实例化对象,然后调用save方法插入
let stu = new stuModel({
	name:'xyj',
	age:23
})
stu.save(function(err){
 console.log(err);//传入一个回调函数,接受返回值
})


//查询语句
stuModel.find(function(err,stu){
	if(err){
		console.log(err);
	}else{
		console.log(stu);
	}
})


//根据ID删除
stuModel.findByIdAndRemove('5dce0c19385ddf5cf4e29aa1',function(err){
if(err){
	console.log(err)
}else{
	console.log('删除成功')
}
})


//根据ID更新、第二个参数为更新的字段
stuModel.findByIdAndUpdate('5dce14dd021afc206406e195',{name:'xyjjjjjjj'},function(err){
	if(err){
		console.log(err);
	}else{
		console.log('更新成功');
	}
})


------------------------
//关联查询
//创建两个集合映射Schema,将需要关联的字段添加ref: 'class2'关联class2集合
//学生表
var stuSchema =  mongoose.Schema({
    name:String,
    age:Number,
    class: { type: mongoose.Schema.Types.ObjectId, ref: 'class2' }
},{collection:'student'})


//班级表
var classSchema =  mongoose.Schema({
    name:String,
    banzhuren:String
},{collection:'class2'})


var claModel = mongoose.model('class2',classSchema);
var stuModel =  mongoose.model('stu',stuSchema);

//插入年级数据
// var cla = new claModel({
//     name:'三年一班',
//     banzhuren:'Miss.huang'
// })

// cla.save(function(cc){
//     console.log(cc)
// })

//插入学生数据
// var stu = new stuModel({
//     name:'刘能',
//     age:31,
//     class:'5dd5f712b55aa463058dde07'
// })

// stu.save(function(err,stu){
//     console.log(stu)
// })

//使用populate将关联的表对应的字段查询出来
stuModel.find({'name':'赵四'}).populate('class').exec(function(err,stu){
   console.log(stu)
})
//使用populate将关联的表对应的字段查询出来
stuModel.find({'name':'刘能'}).populate('class','name').exec(function(err,stu){
    console.log(stu)
})

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值