上传文件以替换数据库中的表的问题

时间:2013-12-11 17:45:06

标签: node.js web-applications file-upload express mongoose

我正在尝试上传包含多个对象数组的文件,并使用它来替换我的mongoose数据库中的表。这就是文件的样子:

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!");
    });
}

但我得到了这个错误

sarah@superawesome:~/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)

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

你需要摆脱

var newRooms = 

JSON.parse无法将其解析为有效的json字符串。

答案 1 :(得分:0)

第一个文件是javascript,而不是JSON。

如果它打算成为JSON,那就这样做:

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