//进行以下操作时,先安装mongodb模块
cnpm install mongodb -S
//从mongodb里边获取MongoClient(客户端)
const mongoClient = require("mongodb").MongoClient ;
//定义连接的数据库
const db_name = "name" ;
//定义连接的数据库中的表格
const db_collection = "studenss" ;
打开数据库以后操作
mongoClient.connect(data_url,(err,client) => {
//MongoClient(客户端)连接数据库地址
if(err) throw new Error(err) ;
//如果异常则抛出异常
const collection = client.db(db_name).collection(db_collection) ;
//连接数据库 和 连接数据库中的表
//collection就是数据库中的表(BK1910.studenss)
//增 删 改 查
})
//所有的增删改查 都需要在MongoClient(客户端)连接数据库地址成功后的回调函数内填写(也就是在上边空出来的位置中填写)
//增
collection.save({ username: "aaa", password: "111" }, (err, result) => {
if (err) throw new Error(err);
client.close();
});
//删
// collection.remove({username:"aaa"} , (err) => {
// client.close() ;
// })
//改
collection.update({ name: "钱九九" }, { $set: { name: "钱十" } }, (err, result) => {
client.close();
}, false, true);
//查
collection.find().toArray((err, result) => {
console.log(result);
})