node.js使用mongoose模块建立数据库连接到mongoDB

const  mongoose  = require('mongoose');	//导入mongoose模块

mongoose.connect('mongodb://localhost/playground',{			

	//使用mongoose 的connect方法,第一个参数是连接一个数据库,如果数据库不存在就建立一个
 useNewUrlParser: true, 
 useUnifiedTopology: true   })
	.then(()=>console.log('数据库连接成功'))
	.catch(err =>console.log(err,'数据连接失败'))

const courseSchema = new mongoose.Schema({		//Schema  是建立一个集合规则
	name : String,
	school : String,
	isshowed: Boolean
});

const Course = mongoose.model('Course',courseSchema);	//model方法是建立一个集合的构造函数

const course = new Course({	//集合的实例化
	name: 'Harris',
	school : 'WUST',
	isshowed: true
})
course.save();	//保存

node.js使用mongoose模块建立数据库连接到mongoDB_mongodb

node.js使用mongoose模块建立数据库连接到mongoDB_构造函数_02

创建文档的第二种方式:

Course.create({
		name : 'yyyyy',
		school: 'WUST',
		isshowed: true
	},(err,doc)=>{
		console.log(err);
		console.log(doc);
	})

利用构造函数的create 方法。
node.js使用mongoose模块建立数据库连接到mongoDB_构造函数_03
node.js使用mongoose模块建立数据库连接到mongoDB_数据库_04
也可以使用Promise对象的方式then,catch

Course.create({
		name : 'zzzzz',
		school: 'WUST',
		isshowed: true
	}).then(res=>{
		console.log(res);
	});