第三方模塊庫(kù)
使用第三方模塊mongoose
- 安裝
# npm install mongoose
- 實(shí)例
var mongoose = require('mongoose');
//創(chuàng)建一個(gè)鏈接流椒,并選擇數(shù)據(jù)庫(kù)
var db = mongoose.createConnection('mongodb://localhost:27017/test');
//設(shè)置數(shù)據(jù)類(lèi)型
var monSchema = new mongoose.Schema({
name:{type:String,default:'liuyanming'},
age:{type:Number,min:1,index:true},
sex:{type:String}
});
//選擇集合
var monmodel = db.model('users',monSchema);
(1)插入數(shù)據(jù)
var content = {name:'劉先生',age:10,sex:'男'};
var monInsert = new monmodel(content);
monInsert.save(function(err){
if(err){
console.log(err);
}else{
console.log('save data is successful');
}
db.close();
});
(2) 查詢(xún)數(shù)據(jù)
var condition = {name:'劉先生'};
var field = {name:1,age:1,sex:1};
monmodel.find(condition,field,function(err,result){
if(err){
console.log(err);
}else{
console.log(result);
}
db.close();
});
(3) 更新數(shù)據(jù)
var condition = { _id: '57dea86e0168d037f3445f69' };
var setData = { name: 'aaa', sex: 'male', age: '500' };
monmodel.update(condition,{$set:setData},function(err,result){
if(err){
console.log(err);
}else{
console.log(result);
}
db.close();
});
(4) 刪除數(shù)據(jù)
var condition = { _id: '57dea86e0168d037f3445f69' };//條件
monmodel.remove(condition,function(err,result){
if(err){
console.log(err);
}else{
console.log(result);
}
db.close();
});
使用第三方模塊mongodb
- 安裝
# npm install mongodb
- 實(shí)例:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://127.0.0.1:27017/test';
MongoClient.connect(url,function(err,db){
if(err){
console.log(err);
}else{
console.log('success');
db.close();
}
});
其他用到的東東
-
url 模塊
var urlapi = require('url'); var url = urlapi.parse(req.url); //獲取當(dāng)前url的信息 var urlPath = url.pathname;
-
querystring 模塊
var querystring = require('querystring'); var query = querystring.parse(url.query);//結(jié)合url 獲取參數(shù) var data = querystring.parse(formData);
-
獲取post數(shù)據(jù)
var formData = ''; req.on('data',function(data){ formData+=data; });//接收post數(shù)據(jù)的過(guò)程 req.on('end',function(){ var data = querystring.parse(formData);//獲取到的數(shù)據(jù)需要處理一下 //數(shù)據(jù)接收完畢们衙,事務(wù)處理 });
遇到的問(wèn)題:
-
修改刪除的時(shí)候顯示OK:1囊卜,但是并沒(méi)有刪除或者修改琅攘。用到
mongoose.Types.ObjectId(str);
解決方案如下:var id = mongoose.Types.ObjectId(query.id); //轉(zhuǎn)換一下獲取的ID var condition = {_id:id};
錯(cuò)誤信息就不貼了做个,解決就是每次執(zhí)行只能有一個(gè)res.end();