node链接mongodb数据库

第一步:在node环境下下载mongodb的包

npm install mongodb

第二步:建立一个js文件里面进行数据库链接等操作

var http= require("http");

var MongoClient=require("mongodb").MongoClient;
//使用mongodb包的MongoClient
var url = "mongodb://localhost:27017/";
MongoClient.connect(url,function(err,db){//db指的是 连接的数据库容器   [ 数据库  ]
	if(err) throw err;
	console.log("链接成功");
	// db.close();// 关闭数据库[容器]
	var dbase=db.db("runoob");
	//数据库【容器】.数据库(“数据库名字”) 
	dbase.createCollection("student",function(err,res){
	// 创建集合【表】 在数据库("runoob")中创建student表
	 	if(err) throw err;
	 	console.log("创建了 表格");
	 	db.close()
	 })
	//插入数据
	dbase.collection("student").insertOne({name:"张三",sex:"男",class:"7"},function(err,res){

	 	if(err) throw err;
	 	console.log("插入完成");
	// 	db.close()
	 }),
	 //插入多行
	dbase.collection("student").insertMany([
	 	{name:"牛德庆",sex:"男",class:"7"},
	 	{name:"喜洋洋",sex:"男",class:"7"},
	 	{name:"数字也",sex:"男",class:"7"},
	 	{name:"华凌",sex:"男",class:"7"}
	 ],function(err,res){

	 	if(err) throw err;
	 	console.log("多条插入完成");
	// 	db.close()
	})
	//查找
	 dbase.collection("student").find({name:"张三"}).toArray(function(err,res){
	 	if(err) throw err
	 	console.log(res);//查到的数据
	 })
	//排序
	 dbase.collection("student").find({name:"张三"}).sort({type:1}).toArray(function(err,res){
	 	if(err) throw err
	 	console.log(res);//查到的数据
	 })
	//跳过几个再找
	dbase.collection("student").find({name:"张三"}).skip(1).toArray(function(err,res){
	 	if(err) throw err
	 	console.log(res);//查到的数据
	 })
	//修改 一个
	dbase.collection("student").updateOne({name:"张三"},{$set:{class:"888"}},function(err,res){
	 	if(err) throw err;
	 	console.log("修改完成");
	 	console.log(res);
	// 	db.close()
	})
	//删除
	 dbase.collection("student").deleteMany({name:"张三"},function(err,res){
		if(err) throw err;
		console.log("删除完成");
	//	db.close()
	})
	//限制limit
	dbase.collection("student").find().limit(4).toArray(function(err,res){
		if(err) throw err;
		console.log(res);
		db.close()
	})
})

http.createServer(function(req,res){
	// res.writeHead(200,{"Content-type":"*"});
	// var a="hellow“;
	// res.write(a)
	// res.end();
}).listen(8081)
console.log("正在奔跑")

在这里插入图片描述
我们连接的是 数据库容器 【 链接时候参数db 可变的】
在容器中 有很多的数据库【db 固定】
数据库中有很多的表【集合 collection】

之后就是对表的操作 例如增删改查

注意db.close() 不能乱写 当要做的事运行完时候在进行关闭

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值