I'm trying to set up javacript file to seed my mongodb with a few entries. I have two schema, boat and cable. Each boat will have multiple cables. I'm trying to cables to the boat entry by looping through a small array. Currently there is only one boat but once I get this working its likely that I'll add in more boats.
The issue I'm having is that although it looks like the script runs correctly with my conosle.logs what is actually saved to mongo includes duplicate entries for cables. Here is my code:
var mongoose = require("mongoose");
var Cable = require("./models/cable");
var Boat = require("./models/boat");
var boatData = [
{
sfBoatID: "AA112233",
currentName: "Hanuman",
cables:[]
}
]
var cableData = [
{
sfBoatID: "AA112233",
cableID: "154705-1",
jobNumber: "154705",
jobName: "Hanuman A0",
productType: "TorqueLite 2.0",
cableName: "A0 TDT",
length: "30.12"
},
{
sfBoatID: "AA112233",
cableID: "154705-2",
jobNumber: "154705",
jobName: "C0 Hanuman TCT",
productType: "TorqueLite 2.0",
cableName: "C0",
length: "34.0"
},
{
sfBoatID: "AA112233",
cableID: "155809-1",
jobNumber: "155809",
jobName: "Hanuman J4",
productType: "TorqueLite 2.0",
cableName: "J4 BUT",
length: "23.00"
}
];
console.log("==============================================")
function seedDB() {
Boat.create(boatData[0], function(err, boat){
if(err) {
console.log(err);
}else{
cableData.forEach(function(seed){
Cable.create(seed, function(err, cable){
if(err){
console.log(err);
}else{
}
boat.cables.push(cable)
boat.save();
console.log(boat)
})
})
}
})
}
module.exports = seedDB;
The console.log(boat) at the end looks ok, it outputs like this:
{ __v: 0,
sfBoatID: 'AA112233',
currentName: 'Hanuman',
_id: 58fcba3979dd1d010043318a,
cables:
[ 58fcba3979dd1d010043318b,
58fcba3979dd1d010043318d,
58fcba3979dd1d010043318c ] }
So 1 boat, 3 cables, about what I was expecting. The problem is that the mongo entry has 6 entries:
> db.boats.find()
{ "_id" : ObjectId("58fcbcab8d4fdb2e7c5d283c"), "sfBoatID" : "AA112233", "currentName" : "Hanuman", "cables" : [ ObjectId("58fcbcab8d4fdb2e7c5d283d"), ObjectId("58fcbcab8d4fdb2e7c5d283d"), ObjectId("58fcbcab8d4fdb2e7c5d283e"), ObjectId("58fcbcab8d4fdb2e7c5d283d"), ObjectId("58fcbcab8d4fdb2e7c5d283e"), ObjectId("58fcbcab8d4fdb2e7c5d283f") ], "__v" : 3 }
So it looks like maybe the way it is saving is an issue? Where it saves each loop so adds the new entries to the prvious ones? I've tried moving the save around but haven't had any luck.
Any help greatly appreciated. It might be that there is a better way to do this entirely - I'm pretty new to web development.
Nick
via Nick Christensen
No comments:
Post a Comment