nodejs对mongodb的基本操作
安装组件
nodejs对mongodb的操作需要安装必要的组件,这能减少开发时间
先安装mongodb组件:
npm install mongodb --save
再安装mongoose
npm install mongoose
mongoose对mongodb的增删查改
引入模块并初始化
var mongoose = require('mongoose');
var db = mongoose.createConnection('mongodb://192.168.230.131:27017/test');
var monSchema = new mongoose.Schema({
name:{type:String,default:'戴焕其'},
age:{type:Number},
sex:{type:String}
});
var monModel = db.model('user',monSchema);
添加记录
var content = {name:'小李子',age:18,sex:'男'};
var monInsert = new monModel(content);
monInsert.save(function(err){
if(err){
console.log(err);
}else {
console.log('写入成功');
}
db.close();
});
查找记录
var content = {name:'陈大哥'};
var field = {name:1,age:1,sex:1};
monModel.find(content,field,function(err,result){
if(err){
console.log(err);
} else {
console.log(result);
}
db.close();
});
更新
var tiaojian = {name:'小李子'};
var gengxindata = {$set:{name:'打不死的小强'}};
monModel.update(tiaojian,gengxindata,function(err){
if(err){
console.log(err);
}else {
console.log('更新成功');
}
db.close();
});
删除
var tiaojian = {name:'小李子'};
monModel.remove(tiaojian,function(err){
if(err){
console.log(err);
}else {
console.log("remove is ok!");
}
db.close();
});