nodejs 使用mongoose 操作mongodb
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);
});
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。