// load mongoose module
var mongoose = require("mongoose");
// schema creator -> objectj
var Schema = mongoose.Schema;
// team schema
var TeamSchema = new Schema(
{
name: {
type: String,
required: true
}
}
);
// employees schema
var EmployeeSchema = new Schema(
{
name: {
first: {
type: String,
required: true
},
last: {
type: String,
required: true
}
},
// this will be a MongoDB unique identifier
team: {
// this is how we can create a reference to another document/schema
type: Schema.Types.ObjectId,
ref: "Team"
},
image: {
type: String,
default: "images/user.png"
},
address: {
lines: {
type: [String]
},
postal: {
type: String
}
}
}
);
// team model
var Team = mongoose.model("Team", TeamSchema);
// employee model
var Employee = mongoose.model("Employee", EmployeeSchema);
// insert teams
function insertTeams(callback) {
Team.create([{name: "Product Development"}, {name: "Dev Ops"}, {name: "Accounting"}], function (error, pd, devops, acct) {
if (error) {
return callback(error);
} else {
callback(null, pd, devops, acct);
}
});
}
// insert employees
function insertEmployees(pd, devops, acct, callback) {
Employee.create([
{
name: {
first: "John",
last: "Adams"
},
team: pd._id,
address: {
lines: ["2 Lincoln Memorial Cir NW"],
postal: "20037"
}
}, {
name: {
first: "Thomas",
last: "Jefferson"
},
team: devops._id,
address: {
lines: ["1600 Pennsylvania Avenue", "White House"],
postal: "20500"
}
}, {
name: {
first: "James",
last: "Madison"
},
team: acct._id,
address: {
lines: ["2 15th St NW", "PO Box 8675309"],
postal: "200007"
}
}, {
name: {
first: "James",
last: "Monroe"
},
team: acct._id,
address: {
lines: ["1850 West Basin Dr SW", "Suite 210"],
postal: "20242"
}
}
], function (error, johnadams, thomasjefferson, jamesmadison, jamesmonroe) {
if (error) {
return callback(error);
} else {
callback(null, {
team: pd,
employee: johnadams
}, {
team: devops,
employee: thomasjefferson
}, {
team: acct,
employee: jamesmadison
}, {
team: acct,
employee: jamesmonroe
});
console.log("Employess succesfully added");
}
}); // posible ";" aqui
}
/*** Mongoose DB Connection ****/
var db = mongoose.connection;
// connect to the database
mongoose.connect(dbUrl, function (err) {
// handle the error
if (err) {
return console.error("there was a problem connecting to the database " + err);
}
// if no errors, print connected
console.log("connected");
insertTeams(function (err, pd, devops, acct) {
if (err) {
return console.log(err);
}
insertEmployees(pd, devops, acct, function(err, result) {
if (err) {
console.error(err);
} else {
}
db.close();
process.exit()
});
});
});