[英]Mean stack can't post to mongodb doesn't seem to do anything, get 0 error
我似乎找不到代碼出了什么問題。 我想做的是能夠通過輸入的數據進行發布,然后在單擊按鈕時它應該進行發布(創建)並保存在mongoDB中。 到目前為止,這是我的代碼。 任何幫助表示贊賞!
HTML(注意:Category.name起作用):
<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!
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.