//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)
})