平均堆栈无法发布到 mongodb 似乎什么也没做,得到 0 错误



我似乎找不到代码有什么问题。我想做的是能够通过输入的数据发布,然后当点击按钮时,它应该发布(创建(并保存在mongoDB中。这是我迄今为止的代码。感谢您的帮助!

Html(注:类别名称有效(:

<section class="wrapper" *ngIf="category">
<h2>Create a new post</h2>
<p>within the category <span class="category">{{ category.name }}</span> </p>
<form>
<input type="text" name="title" placeholder="Title" required autofocus [(ngModel)]="title">
<input type="hidden" name="category" value="{{ category._id }}">
<textarea name="content" placeholder="Post content" required [(ngModel)]="content" ></textarea>
<button (click)="createPost()">Publicera</button>
</form>
</section>

组件ts文件:

export class CreateComponent implements OnInit {
category: Category;
title: String = '';
content: String = '';
constructor(
private route: ActivatedRoute,
private appService: AppService
) { }
ngOnInit() {
let _id = this.route.snapshot.paramMap.get('_id');
this.appService.getCategory(_id)
.subscribe(data =>this.category=data);
}
createPost(){
let post = new Post();
post.title = this.title;
post.content = this.content;
this.appService.createPost(post);
}
}

服务文件:

createPost(post: Post){
let payload = {
"title": post.title,
"content": post.content
}
this.http.post(this.apiUrl+"/post/", payload, {responseType: 'text'}).subscribe(response => {});
}

服务器文件(Server.js(

app.post('/api/post', (req, res) => {
var today = new Date();
var newPostData = { userId: req.body.userId, category: req.body.category, postId: req.body.postId, commentId: req.body.commentId, title: req.body.title, content: req.body.content, publishedDate: today, editedDate: null };
var post = new Post(newPostData, function(err) {
});
post.save();
});

我认为您必须在保存函数中添加回调,请查看此处的文档。

var newPostData = { userId: req.body.userId, category: req.body.category, postId: req.body.postId, commentId: req.body.commentId, title: req.body.title, content: req.body.content, publishedDate: today, editedDate: null };
var post = new Post(newPostData);
post .save(function (err) {
if (err) {console.log(err) return res.send(err)};
// saved!
});

相关内容

  • 没有找到相关文章

最新更新