Mongoose的使用

最近想作一个练手的App小项目。考虑到数据接口的问题,由于关系型数据库用的比较多,也有必定经验了,因此打算使用比较火的MongoDB做为数据库,下面就介绍一下Mongoose的使用方法吧。node

概念:Mongoose是MongoDB的一个对象模型工具,能够工做于异步环境下。数据库

1、建立数据库npm

2、使用Mongoose链接到数据库异步

  安装:$ npm install mongdb 和 $ npm install mongoosemongoose

 编写代码:工具

 1 var mongoose = require('mongoose');    
 2 
 3 var db = mongoose.createConnection('192.168.6.5','DemoDB','27017'); 
 4 db.on('error',console.error.bind(console,'链接错误:'));
 5 db.once('open',function(){
 6   var UserSchema = new mongoose.Schema({
 7   userName:String,    
 8   password:String
 9   });
10   var UserModel = db.model('users',UserSchema);
11   var UserEntity = new UserModel({userName:'weifengzz',password:'123456'});
12   console.log("entity--------"+UserEntity.userName+"-----"+UserEntity.password);
13   UserEntity.save(function(err) {
14     if (err) handleError(err);
15     console.log('Success');
16   });  
17 });

  启动: $ node index.jsui

3、查看数据是否已经插入spa

 

这样数据就插入完毕3d

相关文章
相关标签/搜索