node.js 中使用mongodb

(1)安装mongodb(ubuntu)

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
sudo apt-get update
sudo apt-get install -y mongodb-org

(2)启动数据库

sudo service mongod start

(3)创建数据库

mongo
use test

(4)安装驱动

sudo npm install mongodb

(5)node.js插入数据

const MongoClient=require('mongodb').MongoClient;
function save(databasename,collectionname,data){
	return new Promise((resolve,reject)=>{
		let url='mongodb://localhost:27017/'+databasename;
		MongoClient.connect(url,(err,db)=>{
			if(err){
				console.log(err);
				reject(err);
				db.close();
			}
			else{
				let collection=db.collection(collectionname);
				collection.insert(data,(err,result)=>{
					if(err){
						console.log(err);
						reject(err);
					}
					else{
						resolve(result);
					}
					db.close();
				});
			}
		});
	});
}
save('test','user',{name:'test',age:30});
相关文章
相关标签/搜索