节点服务器中的javascript语法错误

问题是,当我启动服务器时,我得到下面列出的错误。 我对JavaScript非常陌生,这是由于JavaScript或Nodejs版本的差异吗? 我也尝试更改var更新为[]而不是{} ,但获取服务器启动,但它不会更新/从我们的MongoDB删除数据。 如果有帮助, Recipes.findOneAndUpdate的“食谱”是一个Mongoose模式。

这是来自server.js的函数:

 app.post("/updaterecipe", function(req, res) { var id = req.body.recipeID; console.log("Updating recipe " + id); var recipeName = req.body.recipeName; var categoryID = req.body.categoryID; var recipeInstructions = req.body.recipeInstructions; var ingredientIDs = req.body.ingredientIDs; var options = {new: false}; var update = {recipeName, categoryID, recipeInstructions, ingredientIDs}; console.log(update); Recipes.findOneAndUpdate({recipeID: id}, update, options, function(err) { if (err) { console.log("Unable to update"); console.log(err); } }); res.send(update); }); 

而错误:

 var update = {recipeName, categoryID, recipeInstructions, ingredientIDs}; ^ 

在Module._compile(module.js:443:25)位于:Object.Module._extensions..js(module.js:478:10)处的exports.runInThisContext(vm.js:73:16)处的SyntaxError:Unexpected token在启动时在Function.Module.runMain(module.js:501:10)处的Function.Module._load(module.js:310:12)处的Module.load(module.js:355:32)

这是ES6属性简写:

 var update = {recipeName, categoryID, recipeInstructions, ingredientIDs}; 

来源: http : //es6-features.org/#PropertyShorthand

只需升级到最新版本的节点,你应该很好去。

我认为你的JSON存在问题。 您正在尝试创build一个无用的JSON对象。

以下更改到var更新应该做的伎俩。

 var update = { "recipeName": recipeName, "categoryID": categoryID, "recipeInstructions": recipeInstructions, "ingredientIDs": ingredientIDs }; 

您的更新文档在ES5中无效,因为如前所述, 速记属性名称在(ES6)中是新增的,所以您需要指定“密钥”的名称或升级到使用ES6的Nodejs版本。 也就是说,您还需要使用$set更新操作符,因为如果您无法使用$ -modifier,则查询将执行完整文档replace,用update值replace匹配的文档。

 var update = { "$set": { "recipeName": recipeName, "categoryID": categoryID, "recipeInstructions": recipeInstructions, "ingredientIDs": ingredientIDs } }; 

然后:

 Recipes.findOneAndUpdate({ recipeID: id }, update, options, function(err) { if (err) { console.log("Unable to update"); console.log(err); } });