Mongoose
http://mongoosejs.com/
まず、インストールします
npm install mongoose
MongoDBは何もせずに、直接にアクセスコードを書きます
nano mongoose.js ... var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test01'); var kittySchema = mongoose.Schema({ name: String, age: Number }); kittySchema.methods.speak = function () { var greeting = this.name ? "Meow name is " + this.name : "I don't have a name" console.log(greeting); } kittySchema.statics.findAge10 = function(cb) { this.find({age:10}, cb); } var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { var Kitten = mongoose.model('Kitten', kittySchema); var silence = new Kitten({ name: 'Silence', age: 10 }); console.log(silence.name); silence.speak(); silence.save(function(error, doc){ if (error) throw error; doc.speak(); }); Kitten.find({age:10}, function(error, kittens){ if (error) throw error; //console.log(kittens.length); for(var i = 0; i < kittens.length; i++) { console.log("name=" + kittens[i].name + ", age=" + kittens[i].age); } }); Kitten.findAge10(function(error, kittens){ if (error) throw error; for(var i = 0; i < kittens.length; i++) { console.log("[findAge10]" + "_id=" + kittens[i]._id + ", name=" + kittens[i].name + ", age=" + kittens[i].age); } }); }); ...
MongoDBにコマンドラインで確認
mongo test01 MongoDB shell version: 2.4.6 connecting to: test01 > db.kittens.find(); { "name" : "Silence", "_id" : ObjectId("526363e14c9737ad7d000001"), "__v" : 0 } { "name" : "Silence", "_id" : ObjectId("526364602b72debd7d000001"), "__v" : 0 } { "name" : "Silence", "_id" : ObjectId("526366ac44f9bbdc7d000001"), "__v" : 0 } { "name" : "Silence", "_id" : ObjectId("526366af45401de77d000001"), "__v" : 0 } { "name" : "Silence", "_id" : ObjectId("526366b470beb2f27d000001"), "__v" : 0 } { "name" : "Silence", "_id" : ObjectId("526366e287add0fe7d000001"), "__v" : 0 } { "name" : "Silence", "age" : 10, "_id" : ObjectId("5263677163a5d80d7e000001"), "__v" : 0 } { "name" : "Silence", "age" : 10, "_id" : ObjectId("5263677474f35d187e000001"), "__v" : 0 } { "name" : "Silence", "age" : 10, "_id" : ObjectId("526367783de3c5237e000001"), "__v" : 0 } { "name" : "Silence", "age" : 10, "_id" : ObjectId("526367983c6a5b2f7e000001"), "__v" : 0 } { "name" : "Silence", "age" : 10, "_id" : ObjectId("526367ae080b5c3b7e000001"), "__v" : 0 } { "name" : "Silence", "age" : 10, "_id" : ObjectId("526367c1ab6cf3477e000001"), "__v" : 0 } { "name" : "Silence", "age" : 10, "_id" : ObjectId("52636802f4ac10537e000001"), "__v" : 0 } { "name" : "Silence", "age" : 10, "_id" : ObjectId("5263686f6a20e2657e000001"), "__v" : 0 } >
0 件のコメント:
コメントを投稿