Mongoose“外键”让我的代码变得可怕

时间:2016-09-15 09:12:00

标签: javascript node.js mongodb mongoose promise

我正在使用Node.js 4.x和Mongoose 4.6.0与MongoDB 3.2。

我在我的模型上有关系,当我想要创建一个对象时,我必须创建另一个来链接它们。我必须先检查对象是否不存在然后我创建它并使用创建的_id否则我将使用现有对象_id

例如Office模型

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Create Office schema
var officeSchema = new Schema({
    name        : { type: String, required: true },
    address     : String,
    city        : String,
    zip_code    : String,
    geolocation : [ { type: Schema.Types.ObjectId, ref: 'Geolocation' } ],
    company     : [ { type: Schema.Types.ObjectId, ref: 'Company' } ]
});

var Office = mongoose.model('Office', officeSchema, 'Office');

module.exports = Office;

如你所知,如果我想创建一个Office,我必须创建一个公司和地理位置对象。

所以我遇到了问题,因为我的代码变得不可读且非常同步。我认为有一个更好的解决方案,使我的代码更清洁。例如使用Promise可能吗?但我不知道我怎么能这样做。

我愿意接受所有建议。这是我的代码示例。

app.post('/init/complete', function(req, res){

    var companyName   = toTitleCase(req.body.company);

    // Find or Create Company
    Company.findOne({'name': companyName}, function(err, company){

        if (err) throw err;

        // Check existing Company
        if( !company ){

            var newCompany = Company({
                name: companyName
            });

            // Save the Company
            newCompany.save(function(err, companyCreated) {
                if (err) throw err;

                findOrCreateOffice(companyCreated, req);
            });
        }else{
            findOrCreateOffice(company, req);
        }
    });
});

// Find or create office with the geolocation
function findOrCreateOffice(company, req){

    var officeName  = toTitleCase(req.body.office);
    var address     = req.body.address;
    var city        = req.body.city;
    var zipcode     = req.body.zipcode;
    var latitude    = req.body.latitude;
    var longitude   = req.body.longitude;

    Office.findOne({'name': officeName}, function(err, office){

        if (err) throw err;

        // Check existing Office
        if( !office ){

            // Create new Geolocation
            var newGeoloc = Geolocation({
                latitude: latitude,
                longitude: longitude
            });

            // Save the Geolocation
            newGeoloc.save(function(err) {
                if (err) throw err;

                // Create new Office
                var newOffice = Office({
                    name        : officeName,
                    address     : address,
                    city        : city,
                    zip_code    : zipcode,
                    geolocation : newGeoloc._id,
                    company     : company._id
                });

                // Save the Office
                newOffice.save(function(err, officeCreated) {
                    if (err) throw err;

                    updateUser(officeCreated, req)
                });
            });
        }else{
            updateUser(office, req)
        }
    });
}

// Update User informations
function updateUser(office, req){

    var phone     = req.body.phone;
    var job       = req.body.job;
    var notif     = req.body.notif;

    User.findOne({ 'email' : req.user.email }, function(err, user) {
        if (err) throw err;

        // Update User
        user.phone        = phone;
        user.type         = job;
        user.email_notif  = notif;
        user.account_init = true;
        user.office       = office._id;

        user.save(function(err){
            if(err) throw err;

            res.json('SUCCESS');
        });
    });
}

0 个答案:

没有答案