Friday 14 April 2017

when i add multiple reference in mongoose schema, it gives and undefined _id error

i created a TEAM schema and a Employee schema and n employee schema i gave a reference to Team schema and then i entered three teams and passed them in a callback and when i insert Employees , it runs if i give reference to team as team: pd._id, but when i try to give refence with devops or acft, it throws the error

cannot read property _id of undefined

here is my code from index.js

var http = require('http');
var employeeService = require('./lib/employees');
var responder = require('./lib/responseGenerator');
var staticFile = responder.staticFile('/public');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var db = mongoose.connection;
var dbUrl = 'mongodb://test:test123@ds145780.mlab.com:45780/firstprojecttestdb'


//Team schema

var TeamSchema = new Schema({
    name: {
        type:String,
        required: true
    }
});



//Employee schema

var EmployeeSchema = new Schema({

    name:{
        first:{
            type:String,
            required:true
        },
        last:{
            type:String,
            required:true
        }
    },
    team:{
        type: Schema.Types.ObjectId,
        ref:'Team'
    },
    image:{
        type: String,
        default: 'images/user.png'
    },
    address:{
        lines:{
            type:[String]
        },
        postal:{
            type:String
        }
    }
})



var Team = mongoose.model('Team', TeamSchema);

db.on('error', function (){
    console.log('There was a error connecting the database');
});

var Employee = mongoose.model('Employee', EmployeeSchema);


function insertTeams(callback){
    Team.create([{
        name: 'Product Developement'
    },{
        name:'Dev Ops'
    },{
        name:'Accounting'
    }], function(error, pd, devops, acct){
        if(error){
            return callback(error);
        }else{
            console.log('teams successfully added');
            callback(null, pd, devops, acct);
        }
    });
}

function insertEmployees(pd, devops, acct, callback){
    Employee.create([{
        name:{
            first:'John',
            last:'Adans'
        },
        team: pd._id,
        address:{
            lines:['2 Lincoln Memorial Cir NW'],
            zip:423423
        }
    },{
        name:{
            first:'James',
            last:'Madison'
        },  
        team: pd._id,
        address:{
            lines: ['2 15th St NW', 'PO Box 8675309'],
            zip: 435235
        }
    },{
        name:{
            first:'James',
            last: 'Monroe'
        },
        address:{
            lines:['1850 West Basin Dr SW', 'Suite 210'],
            zip: 204304
        }
    }], function (error, johnadams){
        if(error){
            return callback(error);
        }else{
            console.info('employees seccessfully added');
            callback(null,{

                employee: johnadams
            });
        }
    });
}

mongoose.connect(dbUrl, function(err){
    if(err){
        return console.log('there was a problem connecting the database! ' + err);

    }

    console.log('connected!');


    //this is inseriting employees by caling functions instead of doing it here manuallly

    insertTeams(function (err, pd, devops, acct){
        if(err){
            return console.log(err);
        }

        insertEmployees(pd, devops, acct, function(err, result){
            if(err){
                console.log(err);
            }else{
                console.info('database activity complete');
            }
            db.close();
            process.exit();
        });
    });


    //this is to retrieve data from db


    // this is for inserting one team at a time


    // var team = new Team({
    //  name: 'Product Developement'
    // });

    // team.save(function(error, data){
    //  if(error){
    //      console.log(error);
    //  }else{
    //      console.dir(data);
    //  }

    //  db.close();
    //  process.exit();
    // });




    // to insert multiple teams , we use Team.create

    // Team.create([{
    //  name:'Product Developement'
    // },{
    //  name:'Dev Ops'
    // },{
    //  name: 'Accounting'
    // }
    // ], function (error, pd, devops, acct) {
    //  if(error){
    //      console.log(error);
    //  }else{
    //      console.dir(pd);
    //      console.dir(devops);
    //      console.dir(acct);

    //      db.close();
    //      process.exit();
    //  }
    // });


}); 





http.createServer(function(req, res){
    var _url;
    req.method = req.method.toUpperCase();
    console.log(req.method + ' ' + req.url);
    if(req.method !== 'GET'){
        res.writeHead(501, {'Content-Type' : 'text/plain'});
        return res.end(req.method() + ' is not server by this server');
    }
    if(_url = /^\/employees$/i.exec(req.url)){
        //return a list of employees
        employeeService.getEmployees(function(error,data){
            if(error){
                //send a 500 error
                return responder.send500(error,res);
            }
            //send data with 200 status code
            return responder.sendJson(data,res);
        });
    }else if(_url =  /^\/employees\/(\d+)$/i.exec(req.url)){
        //find employee by id in the route
        employeeService.getEmployee(_url[1], function(error,data){
            if(error){
                //send 500 error
                return responder.send500(error,res);
            }
            if(!data){
                //send 404 error
                return responder.send404(res);
            }
            //send data with 200 status code
            return responder.sendJson(data,res);
        });
    }else{
        //try to send a static file
        //if not send 404
        res.writeHead(200);
        res.end('static file maybe')

    }
}).listen(1337);
console.log("server running");



via Abhansh Giri

No comments:

Post a Comment