簡體   English   中英

如何在我的 Express 路由器中使用兩個 MongoDB 集合?

[英]How to use two MongoDB collections in my Express router?

 router.get('/home', ensureAuthenticated, (req, res) => res.render('home', {user_mv: req.user, post_mv: req.post1})); //Create topic page router.get('/create-topic', ensureAuthenticated, (req, res) => res.render('create-topic', {user_mv: req.user})); //Post handle router.post('/create-topic', (req, res) => { const {user_id, title, category, vista, description} = req.body; let error2= []; if(!title || !category || !vista || !description) { error2.push({msg: 'Please check all fields.'}); }; if(error2.length > 0){ res.render('create-topic', { error2, title, category, vista, description }); }else { //Validation passed Post.findOne({title: title}) .then(post1 => { if(post1){ //User exists error2.push({msg: 'Title is already used.'}); res.render('create-topic', { error2, title, category, vista, description }); } else { const newPost = new Post({ user_id, title, category, vista, description }); newPost.save() .then(post1 => { res.redirect('/home'); }) .catch(err => console.log(err)); }; }); }; }); module.exports = router;
 <div class="posts__content"> <a href="#"> <h3><%= post_mv.title %></h3> </a> </div>
當登錄到我的網站時,用戶可以創建一個包含用戶 ID 的帖子插入到 MongoDB 中。 我正在嘗試顯示我收藏中的 1 個帖子的標題,但出現錯誤,提示“無法讀取未定義的“標題”屬性。 誰能告訴我我做錯了什么?

看起來您沒有將帖子傳遞給您的 ejs。 所以沒有 post_mv 對象,所以它沒有定義並且沒有屬性。

res.redirect('/home',{post_mv:post1});

我可能是錯的,但 post1 應該是新的 post 對象,你想要的標題是保存后返回的屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM