【发布时间】:2019-05-16 20:35:00
【问题描述】:
总的来说,我对 Mongoose 还是有点陌生。我正在构建我的博客应用程序,它具有基于 Node 和 MongoDB 的后端,我正在使用 Angular 作为前端。
我正在创建我的 Restful API,它应该允许用户点击帖子并更新它。但是,我不确定我在这里的做法是否正确。
这是我的帖子的架构:
const mongoose = require('mongoose');
// Schema Is ONly bluePrint
var postSchema = mongoose.Schema({
title: {type: String, required: true },
content: {type: String, required: true},
}, {timestamps: true});
module.exports = mongoose.model("Post", postSchema);
在我的角度服务中,我有这个函数可以帮助我将http请求发送到我的后端服务器,这个函数的id来自后端mongoDB,标题和内容来自页面上的表单
updatePost(id: string, title: string, content: string) {
console.log('start posts.service->updatePost()');
const post: Post = {
id: id,
title: title,
content: content
};
this._http.put(`http://localhost:3000/api/posts/${id}`, post)
.subscribe(res => console.log(res));
}
在我看来,至少有几种方法可以创建我的 API
方法 1(有效,但高度怀疑这是否是好的做法): 在这里,我通过我的 service.ts 文件将从 mongoDB 检索到的 id 传递回服务器,以避免“修改不可变字段 _id”错误
app.put("/api/posts/:id", (req,res)=>{
console.log('update api called:', req.params.id);
const post = new Post({
id: req.body.id,
title: req.body.title,
content: req.body.content
});
Post.updateOne({_id: req.params.id}, post).then( result=> {
console.log(result);
res.json({message:"Update successful!"});
});
});
方法 2 我认为这比方法 1 更稳健,但我仍然认为它不是好的做法:
app.put("/api/posts/:id", (req, res)=> {
Post.findOne(
{_id:req.params.id},(err,post)=>{
if(err){
console.log('Post Not found!');
res.json({message:"Error",error:err});
}else{
console.log('Found post:',post);
post.title=req.body.title;
post.content=req.body.content;
post.save((err,p)=>{
if(err){
console.log('Save from update failed!');
res.json({message:"Error",error:err});
}else{
res.json({message:"update success",data:p});
}
})
}
}
);
});
我对所有意见持开放态度,希望我可以向Mongoose和Restful的大师学习一些东西:)
【问题讨论】:
标签: node.js angular mongodb rest mongoose