MongoDB
-
mongod --dbpath=/data --port 27017 可以修改端口号(不提倡修改)
-
var MogoClient = require('mongodb').MongoClient
.asport =require('asmert'); -
mongoose
$ npm install mongoose 依赖于MongoDB
组件可以在任何一个项目中使可以使用,而插件就不能了 -
mkdir zhouyi
-
cd zhouyi
-
npm install mongodb 安装模板
-
npm install mongoose 安装 原生态
启动数据库
- cd mongodb
- ./mongod --dbpath=../liu_db
-
var mongoose = require("mongoose");
-
var db =
mongoose.createConnection('mongodb://192.168.170.131:27017/test'); test数据库 -
console.log(db);
添加
-
var mongoose = require('mongoose');
-
var db = mongoose.createConnection('mongodb://192.168.84.128:27017/test');
-
var monSchema = new mongoose.Schema({
-
name:{type:String,default:'liu'},
-
age:{type:Number},
-
sex:{type:String},
}); -
var monModel =db.model('user',monSchema);
-
var content = {name: "yihao",age:18,sex:'男'};
-
var monInsert = new monModel(content);
-
monInsert.save(function(err)){
-
if(err){
-
console.log(err);
-
}
-
else{
-
console.log('成功');
-
}
-
db.close(); 关闭数据库
-
}
-
show dbs;
-
use test
-
show collections;
-
db.users.find().toArray();
查询
-
var mongoose = requier ('mongoose');
-
var db = mongoose.createConnetion('mongodb://192.168.170.131:27017/test');
-
var monSchema = new mongoose.Schtema({
-
name:{type:String,default:'liu'},
-
age:{type:Number},
-
sex:{type:String}
-
});
-
var monModer = db.model('user',monSchema);
-
var content ={}; //显示什么
-
var field ={name:1,age:2,sex:1}; //要显示出来的内容
-
monModel.find(content,field,function(err,result){
-
if(err){
-
console.log(err);
-
}
-
else{
-
cosole.log(result);
} -
db.close();
});
修改 更新
- var mongose = require('mongoose');
- var db = mongoose.createConnectio('mongodb://192.168.170.131:27017/test');
- ar monSchema = new mongoose.Schema({
- name:{type:String,default:'liu'},
- age:{type:Number},
- sex:{type:String}
});
-
var monModel = db.model('user',monSchema);
-
var tiaojian ={name:"liu"};
-
var gengxindata={$set:{name:'liuy'}};
-
monModel.update(tiaojian,gengxindata ,function(err,result){
- if(err){
- console.log(err);
} - else{
- console.log(result);
}
1 db.close(); //结束
})
删除
-
var mongoose = require('mongoose');
-
var db= mongoose.createConnection('mongodb://192.168.170.131:27017/test');
-
var monSchema = new mongoose.Schema({
- name:{type:String,default:'liu'},
- age:{type:Number},
- sex:{type:String},
});
-
var monModel = db.model('user',monSchema);
-
var shanchu = {name:"liuy"}
-
monModel.remove(shanchu,function(arr,result){
-
for(err){
-
console.log(err);
} -
else{
-
console.log(result);
} -
db.close();
})
网友评论