Page 131 - Node.js开发指南
P. 131

124  第 5 章  使用 Node.js 进行 Web 开发


                   if (time) {
                     this.time = time;
                   } else {
                     this.time = new Date();
                   }
                 };
                 module.exports = Post;

                 Post.prototype.save = function save(callback) {
                   // 存入 Mongodb 的文档
                   var post = {
                     user: this.user,
                     post: this.post,
                     time: this.time,
                   };
                   mongodb.open(function(err, db) {
                     if (err) {
                       return callback(err);
                     }
                     // 读取 posts 集合
                     db.collection('posts', function(err, collection) {
                       if (err) {
                         mongodb.close();
                         return callback(err);
                       }
                       // 为 user 属性添加索引
                       collection.ensureIndex('user');
                       // 写入 post 文档
                       collection.insert(post, {safe: true}, function(err, post) {
                         mongodb.close();
                         callback(err, post);
                       });
                     });
                   });
                 };

                 Post.get = function get(username, callback) {
                   mongodb.open(function(err, db) {
                     if (err) {
                       return callback(err);
                     }
                     // 读取 posts 集合
                     db.collection('posts', function(err, collection) {
                       if (err) {
                         mongodb.close();
                         return callback(err);
                       }
   126   127   128   129   130   131   132   133   134   135   136