mongodb3.2在linux下安装及node操作mongodb实例

来源:互联网 发布:东邪西毒 欧阳锋 知乎 编辑:程序博客网 时间:2024/06/06 01:20

1.解压tar.gz

cd /usr/localtar -zxvf  mongodb-linux-x86_64-rhel62-3.2.0.tgzmv mongodb-linux-x86_64-rhel62-3.2.0 mongodb


2.配置文件vi /etc/mongodb.conf

dbpath=/usr/local/mongodb/datalogpath=/usr/local/mongodb/logs/log.logport=40502fork = true  #以守护程序的方式启用,即在后台运行nohttpinterface = true logappend = truestorageEngine = wiredTigerwiredTigerCacheSizeGB = 1

3.启动mongodb并配置权限

cd /usr/local/mongodb/bin./mongod -f /etc/mongodb.conf  #noauth模式启动

客户端连接登陆 ./mongo localhost:40502

>use admin

>db.createUser({user: "admin",pwd: "12345678",roles:[{ role: "root", db: "admin" }]})

>use test

>db.createUser({user: "root",pwd: "12345678",roles:[{ role: "dbOwner", db: "test" }]})


4.重启mongodb

./mongod -f /etc/mongodb.conf --auth

推荐用客户端工具mongochef连接mongodb3.2,我这边测试的时候发现用mongovue已经不能连接上mongodb3.2了(鉴权失败)。


5.node实例

npm install mongoose

vi test.js

var mongoose = require("mongoose"); var db = mongoose.connect("mongodb://root:12345678@localhost:40502/test"); db.connection.on("error", function (error) { console.log("数据库连接失败:" + error); }); db.connection.on("open", function () { console.log("——数据库连接成功!——"); var TestSchema = new mongoose.Schema({    name : {type:String},    age : {type:Number,default:0},    email : {type:String},    time : {type:Date,default:Date.now}});var TestModel = db.model("test1",TestSchema); //'test'相当于collectionvar TestEntity = new TestModel({    name:'helloworld',    age:28,    emial:'helloworld@qq.com'});TestEntity.save(function(err,doc){    if(err){        console.log("error :" + err);    } else {        console.log(doc);    }});});



0 0
原创粉丝点击