nodejs 使用mongoose 操作mongodb

fudirong 2012-04-12

nodejs操作mongodb可以使用mongoose:

MongooseisaMongoDBobjectmodelingtooldesignedtoworkinanasynchronousenvironment.

安装mongoose:

npminstallmongoose

///获取mongodb连接

varconn=mongoose.connect('mongodb://localhost/mytest');

varSchema=mongoose.Schema

,ObjectId=Schema.ObjectId;

varPerson=newSchema({

title:{type:String}

,age:{type:Number,min:5,max:20}

,meta:{

likes:[String]

,birth:{type:Date}

}

});

varp=mongoose.model('ModelName22',Person);

varBlog=mongoose.model("ModelName22");

//保存新纪录

varblog1=newBlog();

blog1.id22=4;

blog1.title="ully";

blog1.save(function(err){

if(err){

console.log('savefailed');

}

console.log('savesuccess');

});

///查找记录

Blog.find({_id:'4f8678891256c4b819000002'},function(err,docs){

console.log(docs);

});

//修改记录

varconditions={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);

});

相关推荐

hanyueqi / 0评论 2019-06-28