2013-12-11 1 views
0

여러 개체의 배열을 포함하는 파일을 업로드하고이를 내 몽구스 데이터베이스의 테이블을 바꾸는 데 사용하려고합니다. 이 파일이 모습입니다 같은 :데이터베이스의 테이블을 바꿀 파일 업로드 관련 문제

var newRooms = [ 
    {name: "yogaStudio", 
    title: "Yoga Studio", 
    description: "This is where StarFleet officers go to get bendy", 
    roomExits: ['kitchen', 'foyer'],} 
    , 

    {name: "kitchen", 
    title: "Kitchen", 
    description: "You must be starving, please come in and make yourself a sandwich", 
    roomExits: ['yogaStudio', 'drawingroom'],} 
    , 

    {name: "foyer", 
    title: "Foyer", 
    description: "This is the entrance hallway", 
    roomExits: ['yogaStudio', 'kitchen'],}, 

    {name: "drawingroom", 
    title: "Drawing Room", 
    description: "Please grab a drink and take a seat, it's stressful navigating around this place", 
    roomExits: ['kitchen', 'foyer'],} 
    , 
]; 

이 내가 업로드하고 대체하기 위해 사용하고있는 기능은 다음과 같습니다

var restore = function(req, res) { 
    fs.readFile(req.files.roomFile.path, 'utf8', function (err, data) { 
     if (err) { 
      res.send("File upload error."); 
     } else { 
      overwriteDB(JSON.parse(data), res); 
     } 
    }); 
} 

var overwriteDB = function(newDB, res) { 
    if (!Array.isArray(newDB)) { 
     res.send("Error: Data structure isn't an array."); 
     return; 
    }  
    // Should validate newDB further before deleting old documents. 
    Room.remove({}, function(err) { 
     if (err) { 
      res.send("Error: Couldn't delete all existing documents" + 
      "on restore."); 
      return; 
     } else { 
      console.log("All documents removed before restore."); 
     } 

     newDB.forEach(function(theRoomtoImport) { 
     var theRoom = new Room(theRoomtoImport); 
      theRoom.save(function(err, theRoom) { 
       if (err) { 
        console.log("Failure restoring " + theRoom.name); 
       } else { 
        console.log("Success restoring " + theRoom.name); 
       } 
      }); 
     }); 
     res.send("Restore in progress!"); 
    }); 
} 

는하지만이 오류를

[email protected]:~/comp2406/adventure-ajax-demo$ node app.js 
Express server listening on port 3000 

undefined:1 
var newRooms = [ 
^ 
SyntaxError: Unexpected token v 
    at Object.parse (native) 
    at /home/sarah/comp2406/adventure-ajax-demo/routes/index.js:75:23 
    at fs.js:252:14 
    at Object.oncomplete (fs.js:93:15) 

수있는 사람을 받고 있어요 이 문제를 해결하도록 도와 주시겠습니까?

답변

0

첫 번째 파일은 JSON이 아니라 javascript입니다. 이 JSON, 할 의도 경우

바로이 작업을 수행 :

[ 
    {name: "yogaStudio", 
    title: "Yoga Studio", 
    description: "This is where StarFleet officers go to get bendy", 
    roomExits: ['kitchen', 'foyer'],} 
    , 
    ... 
+0

고마워요! 모든 것을 똑바로 유지하는 것은 까다 롭습니다. 이렇게 배열을 끝내겠습니다.]; 아니면 그냥?] – Sarah

+1

그냥] 웹 기반 json 유효성 검사기를 사용하여 작업을 다시 확인할 수 있습니다. – gmcerveny

1

당신은 JSON.parse이 유효한 JSON 문자열을 구문 분석 할 수 없습니다

var newRooms = 

을 제거해야합니다.