Node + MongoDB实现

很久没更新,今天看到有人评论说很希望能更新下去,最近工作事物繁多,主要又在写C#+Webapi这一块。近来用node+mongoDB写了个微信小程序服务端,就贴在这里替代一下node-mysql这个模块。从应用上来说,mongodb比mysql对中小公司更加友好!尤其是公司里没有对性能追求到极致。
简单的贴一点代码和相应配置。
添加package.json里dependencies

    "mongoose": "4.8.7",

定义data-source.js

(function(){
    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost:27017/test');
    module.exports = mongoose;
})();

定义UserEntity.js

/**
 * Created by HQ on 13/03/2017.
 */
(function () {
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    module.exports = new Schema({
        user_id: String,
        phone: String,
        orders: [String],
        address: [
            {
                address_id: String,
                city: String,
                district: String,
                street: String,
                building: String,
                specific: String,
                default: Boolean
            }
        ],
        create_time: Date,
    });
})();

DAO UserDao.js

/**
 * Created by HQ on 11/03/2017.
 */
(function () {
    "use strict";

    var mongodb = require("./data-source");
    var user_schema = require("./../entity/users");
    var Promise = require("bluebird");
    var User = mongodb.model("User", user_schema);

    User.findByUserId = function (user_id) {
        return User.findOne({ user_id: user_id }).exec();
    };

    User.findByUserIdAndPassword = function (user_id, password) {
        return User.findOne({ user_id: user_id, password: password }).exec();
    };

    User.findOrderIds = function (user_id) {
        return User.findOne({ user_id: user_id }, 'orders').exec();
    };

    User.findInfosById = function (user_id) {
        return User.findOne({ user_id: user_id }, 'phone address name').exec();
    }

    var saveUser = function (user) {
        return new Promise(function (resolve, reject) {
            User.findByOpenId(user.open_id).then(
                function (exist) {
                    if (exist != undefined) {
                        return reject("existed open id" + exist);
                    }
                    let _user = new User();
                    MergeUser(user, _user);
                    _user.create_time = new Date();
                    _user.save().then(resolve, reject);
                },
                reject
            )
        });
    };

    var updateUserPhoneAndAddress = function (user) {
        return User.findOneAndUpdate({ user_id: user.user_id }, {
            $set: {
                phone: user.phone,
                address: user.address,
                name: user.name
            }
        }).exec();
    };

    var updateUserSessionKey = function (user) {
        return User.findOneAndUpdate({ user_id: user.user_id }, {
            $set: {
                session_key: user.session_key
            }
        }).exec();
    };

    var addUserOrder = function (order_id, user_id) {
        return new Promise(function (resolve, reject) {
            User.findByUserId(user_id).then(
                function (user) {
                    user.update({ $push: { orders: order_id } }
                    ).then(resolve, reject);
                },
                function () {
                    reject("user does not exist.")
                }
            );
        });
    };

    module.exports.user = User;
    module.exports.addUserOrder = addUserOrder;
    module.exports.saveUser = saveUser;
    module.exports.updateUserPhoneAndAddress = updateUserPhoneAndAddress;


    function MergeUser(req_model, entity) {
        entity.user_id = req_model.user_id;
        entity.phone = req_model.phone;
        entity.open_id = req_model.open_id;
        entity.session_key = req_model.session_key;
        entity.password = req_model.password;
        entity.name = req_model.name;
        entity.address = req_model.address;
        entity.inviter = req_model.inviter;
    }

})();

定义userroute.js

(function () {
    "use strict";

    var express = require('express');
    var router = express.Router();
    var users_dao = require('../bin/dao/users');

    var log4js = require('log4js');
    var logger = log4js.getLogger("users");

    /* update a user address and phone. */
    router.put('/contact', function (req, res) {
        logger.trace("update contact", req.body, "requester", req.session.user_id);
        let user = req.body;
        user.user_id = req.session.user_id;
        users_dao.updateUserPhoneAndAddress(user).then(function () {
            res.sendStatus(200);
        }, function (err) {
            logger.fatal("update contact failed", err);
            res.status(400).send(err);
        });
    });

    module.exports = router;
})();

你可能感兴趣的:(Node + MongoDB实现)