问题是,当我启动服务器时,我收到下面列出的错误。我是JavaScript的新手,这是由于JavaScript或Nodejs版本的不同?我还尝试将var update更改为[]
而不是{}
,但是它使服务器启动,但是它不会更新/删除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};
^
SyntaxError:意外的令牌, 在exports.runInThisContext(vm.js:73:16) 在Module._compile(module.js:443:25) 在Object.Module._extensions..js(module.js:478:10) 在Module.load(module.js:355:32) 在Function.Module._load(module.js:310:12) 在Function.Module.runMain(module.js:501:10) 在启动时(node.j
答案 0 :(得分:2)
这是ES6属性的简写:
var update = {recipeName, categoryID, recipeInstructions, ingredientIDs};
来源:http://es6-features.org/#PropertyShorthand
只需升级到最新版本的节点,您就应该好了。
答案 1 :(得分:0)
我认为您的JSON存在问题。您正在尝试创建一个荣耀的JSON对象。
var update 的以下更改应该可以解决问题。
var update = {
"recipeName": recipeName,
"categoryID": categoryID,
"recipeInstructions": recipeInstructions,
"ingredientIDs": ingredientIDs
};
答案 2 :(得分:0)
您的更新文档在ES5中无效,因为如前所述here,速记属性名称是(ES6)中的新内容,因此您需要指定“密钥”命名或升级到使用ES6的Nodejs版本。话虽如此,您还需要使用$set
更新运算符,因为如果您未能使用$ -modifier,您的查询将执行完整文档替换,将匹配的文档替换为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);
}
});
然后:
{{1}}