簡體   English   中英

Node js - Push() 函數在參考和 mongodb 中無法正常工作

[英]Node js - Push() Function Not working Correctly with reference and mongodb

我正在使用 ObjectReferences 並將評論數據推送到數據庫,但它不起作用即使正在保存數據,但只添加了“id”,而不是用戶和評論

帶有推送方法的主文件

var Comment = require('./models/comments'),
    Camp = require('./models/user');    
app.post('/camp/:id/comment', (req,res)=>{
Camp.findById(req.params.id, (err, idf)=>{
    if(err){
    console.log(err);
    }else{

    Comment.create(req.body.comment, (err, commentz)=>{
    if(err){
      console.log(err);
    }else{
      console.log(commentz + idf);
      idf.comments.push(commentz)
      idf.save();
      res.redirect('/camp/'+ idf._id)
    }
    })
    }
})
})

對象引用 user.js

    var mongoose = require('mongoose');

var schema = mongoose.Schema;
var blogSchema = new schema({
name : String,
email  : String,
descr : String,  // TEMPORERY
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'

}
],
comments: [
    {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment'
    }
]
});

var Camp = mongoose.model("Camp", blogSchema);
module.exports= Camp;

CommentSchema comments.js

    var mongoose = require('mongoose');

var schema = mongoose.Schema;
var cSchema = new schema({
user : String,
comment  : String,
})

var Comment = mongoose.model("Comment", cSchema);
module.exports =Comment;

主窗體

    <form action="/camp/<%=camp._id%>/comment" method="post" class="form-group">
<div class="form-group">
<input class="form-control" type="text" name="comment[user]" value="" placeholder="Name">
</div>
<div class="form-group">
    <textarea class="form-control" style="height:100px" type="text" name="comment[comment]" value="" placeholder="Your Comment"></textarea>
</div>
<div class="form-group">
<button class="btn btn-primary btn-large btn-block" type="submit" name="submit"> SUBMIT</button>
</div>
</form>

添加到用戶數據庫的唯一ID,不是所有評論,在評論中,收藏數據完美添加

我認為不要使用commentz使用commentz._id並有一個.save回調。 它應該工作。

  console.log(commentz + idf);
  idf.comments.push(commentz._id)
  idf.save(function(err){
    if(err){
      // handle error
    }
    res.redirect('/camp/'+ idf._id)
  });

暫無
暫無

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

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