CRUD用户模型

时间:2014-09-12 06:47:46

标签: javascript mongodb mongoose crud mongodb-java

有人能告诉我CRUD用户模型究竟是如何制作的吗?我的意思是,在这段代码中我该怎么写 “阅读”和“删除”功能?

'use strict';

var User, self,
    q = require('q');

module.exports = User = function (appl) {

    this.db = appl.db;

    this.Model = this.db.model('User', new this.db.Schema({
        name        :   String,
        handle      :   String,
        password    :   String,
        date        :   Date
    }));

    this.ObjectId = this.db.ObjectId;

    self = this;
};

/**
 * @method create
 * @desc Create a user
 * @param arguments {Object} Mongo find query obj
 */
User.prototype.create = function (data) {

    var d = q.defer();

    (new self.Model(data)).save(function (err) {
        return err ? d.reject(err) : d.resolve(data);
    });

    return d.promise;
};


/**
 * @method load
 * @desc Load a user either from Id or title
 * @param arguments {Object} Mongo find query obj
 */
User.prototype.load = function () {

    var d = q.defer();

    self.Model
    .find((arguments && arguments[0]) || {})
    .limit(1)
    .exec(function (err, user) {
        d[err ? 'reject' : 'resolve'](err ? err : user);
    });

    return d.promise;
};

/**
 * @method query
 * @desc Query users
 * @param arguments {Object} {
 *                              query: {Object} Mongo find query object
 *                              limit: {Int} Maxiumum documents to return
 *                           }
 */
User.prototype.query = function () {

    var d = q.defer();

    self.Model
    .find((arguments && arguments[0] && arguments[0].query) || {})
    .limit((arguments && arguments[0] && arguments[0].limit) || null)
    .exec(function (err, users) {
        d[err ? 'reject' : 'resolve'](err ? err : users);
    });

    return d.promise;
};

/**
 * @method update
 * @desc Load a user either from Id or title
 * @param arguments {Object} Mongo find query obj
 */
User.prototype.update = function () {

    var d = q.defer();

    // self.Model
    // .update(self.ObjectId(data._id), {
    //     hello: true
    // });

    return d.promise;
};

0 个答案:

没有答案