nodejs操作mongodb可以使用mongoose:
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment.
安装mongoose:
npm install mongoose
///获取mongodb连接
var conn = mongoose.connect('mongodb://localhost/mytest');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
var Person = new Schema({
title : { type: String }
, age : { type: Number, min: 5, max: 20 }
, meta : {
likes : [String]
, birth : { type: Date }
}
});
var p = mongoose.model('ModelName22', Person);
var Blog = mongoose.model("ModelName22");
//保存新纪录
var blog1 = new Blog();
blog1.id22 = 4;
blog1.title="ully";
blog1.save(function(err){
if (err) {
console.log('save failed');
}
console.log('save success');
});
///查找记录
Blog.find({_id:'4f8678891256c4b819000002'},function(err,docs){
console.log(docs);
});
//修改记录
var conditions = { name: 'borne' }
, update = { $set: { title: 'xxxxb' }}
, options = {};
Blog.update({_id:'4f866f35311977a81b000001'},update,options,function(err,docs){
console.log(docs+","+err);
});
//删除记录
Blog.remove({_id:'4f8678891256c4b819000002'},function(err,docs){
console.log(docs);
});