//链接数据库
mongoose.connect("mongodb://localhost:27017/user");
var db = mongoose.connection;
db.on("error",function(error){
if(error){
return console.log(error);
}
});
db.on("open",function(){
console.log("成功");
});
var Schema = mongoose.Schema({
name:{type:String},
age:{type:Number,default:20}
// bobby:{hobby1:{type:String},hobby2:{type:String}},
},{collection:"person"});
var Model = db.model("person",Schema);
Model.find({},{},function(err,data){
if(err){
return console.log(err);
}else{
console.log(data);
}
});
Model.find({age:{$lt:30}},{name:1},function(err,data){
if(err){
return console.log(err)
}else{
console.log(data)
}
})
Model.find({age:{$gt:20}},null).then((data) =>{
console.log(data);
}).catch((err) =>{
console.log(err);
})
Model.find({$or:[{name:/王/},{name:/李/}]}).then((data)=>{
console.log(data);
}).catch((err)=>{
console.long(err);
});
//添加
Model.create({name:"周鸿祎",age:50},function(err,data){
if(err){
return console.log(err);
}else{
console.log(data);
}
});
//更新
Model.update({name:"甘慧琳"},{$set:{age:21}},{multi:1},function(err,data){
if(err){
return console.log(err)
}else{
console.log(data);
}
})
//删除
Model.remove({name:"马云"},function(err,data){
if(err){
return console.log(err)
}else{
console.log(data);
}
})
//游标操作
Model.find({},{},{sort:{age:-1}},function(err,data){
if(err){
return console.log(err)
}else{
console.log(data)
}
});
Model.find().sort({age:-1}).then(function(data){
console.log(data);
})
Model.find({},{},{sort:{age:-1},skip:2,limit:2},function(err,data){
if(err){
return console.log(err)
}else{
console.log(data)
}
})