我正在尝试使用nodejs创建博客。我可以将文件和数据上传到mongoose成功。我的问题是:我无法编辑数据。
router.post('/admin/create-article',upload.any(), function(req,res,next){
if(req.files){
req.files.forEach(function(file){
var filename = (new Date).valueOf() + "-" + file.originalname;
fs.rename(file.path, 'public/uploads/images/thumbnails/' + filename, function(err){
if(err)throw err;
//save to mongoose
var newArticle = {
title:req.body.title,
featured_image:filename,
article_content:req.body.article_content,
created_at:moment().format('MMMM Do YYY, h:mm:ss a')
};
Article.create(newArticle,function(err,result){
if(err){
}
res.json(result);
});
});
});
}
});
这是编辑(不工作):
router.put('/admin/article/:id/edit',upload.any(), function(req,res,next){
if(req.files){
req.files.forEach(function(file){
var filename = (new Date).valueOf() + "-" + file.originalname;
fs.readFile(file.path, 'public/uploads/images/thumbnails/' + filename, function(err){
// if(err)throw err;
//save to mongoose
var editArticle = {
title:req.body.title,
featured_image:filename,
article_content:req.body.article_content,
created_at:moment().format('MMMM Do YYY, h:mm:ss a'),
};
Article.findByIdAndUpdate(req.params.id, editArticle, function(err,article){
if(err){
rep.flash('error', err.message);
return res.redirect('/article/' + req.params.id);
}
req.flash('success','Articles updated successfully');
console.log('success');
res.redirect('/admin/articles/');
});
});
});
}
});
答案 0 :(得分:1)
如果您使用findByIdAndUpdate
mongoose命令,则应使用$set
运算符。
...
//save to mongoose
var editArticle = {
title : req.body.title,
featured_image : filename,
article_content: req.body.article_content,
created_at : moment().format('MMMM Do YYY, h:mm:ss a'),
};
Article.findByIdAndUpdate(req.params.id, {$set: editArticle}, ...);