启动mongoDB
1、终端中输入mongod
,启动mongo服务端,出现下面的样子就是启动成功了。
2、新建一个终端窗口,输入mongo
,出现下面的样子就是启动成功了。
3、mongo启动成功后,就可以对数据库进行操作了。
点击https://blog.youkuaiyun.com/Charissa2017/article/details/105016264查看mongdb简介及常用的命令
Node连接mongoDB
node连接mongodb,需要使用第三方模块mongoose,mongoose支持promises或者回调。
1、安装
npm install mongoose
或者使用yarn安装
yarn add mongoose
2、使用require引入到模块中
const mongoose=require("mongoose");
3、连接到mongodb
mongodb 终端中输入db.getMongo()
,获取连接地址
nodeJs中,使用connect()方法进行连接。
- 第一个参数为数据库地址,协议是
mongodb:
,host为mongodb的连接地址,后面跟要连接的数据库名称。 - 使用新版本的mongoose,需要在第二个参数option中设置useNewUrlParser和useUnifiedTopology为true。否则将会出现以下警示:
(node:86213) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:86213) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
nodeJs中写入以下代码:
mongoose.connect("mongodb://127.0.0.1:27017/test",{
useNewUrlParser: true,
useUnifiedTopology: true
});
连接后,将open在Connection实例上触发事件,Connection为mongoose.connection。
var db=mongoose.connection;
//连接失败时执行
db.on("error",console.error.bind(console,"connect fail"));
//连接成功后执行
db.on("open",()=>{
console.log("we are connected~")
})
到这里,我们就可以实现node连接mongodb了。
4、通过node操作mongodb
通过mongoose.model()
定义一个模型,mongoose.model()中,
第一个参数为数据库中集合的名称,
第二个参数为该集合中字段的名称和类型。
对数据的操作需要使用promise或者回调函数,如果使用回调函数的话,按照Node错误优先的原则 ,第一个为err,第二个参数为执行操作后返回的内容,跟使用命令行操作mongodb是一样的。
继续上面的文件内容:
//定义一个模型
var UserModel = mongoose.model("users",{
name:String,
age:Number,
sex:String,
address:String
})
//查看当前集合中的所有内容
async function find(){
let rs=await UserModel.find({});
console.log(rs);
}
find();
//添加数据
function add() {
UserModel.insertMany([{ name: 'user5', age: 20 }, { name: 'user6', age: 21 }], function (err, docs) {
console.log(docs);
//[ { _id: 5e7892cc982ba0516ddb16e7, name: 'user5', age: 20, __v: 0 },
//{ _id: 5e7892cc982ba0516ddb16e8, name: 'user6', age: 21, __v: 0 } ]
})
}
add();
//修改数据
async function update(){
let rs=await UserModel.update({name:"zhangsan"},{$set:{age:33}});
console.log(rs); //{ n: 1, nModified: 1, ok: 1 }
}
update();
//删除数据
function del(){
UserModel.deleteMany({name: 'user5'},function(err,docs){
console.log(docs); //{ n: 1, ok: 1, deletedCount: 1 }
})
}
del();
对数据的操作命令可以查看mongoose官网API文档:http://www.mongoosejs.net/docs/api.html#Model