標籤:
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);
});
nodejs 使用mongoose 操作mongodb