简体   繁体   English

Node js - Push() 函数在参考和 mongodb 中无法正常工作

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

I am using ObjectReferences and push the comment data to the database but it's not working Even the data is being saved but only 'id' get added, not the user and comment我正在使用 ObjectReferences 并将评论数据推送到数据库,但它不起作用即使正在保存数据,但只添加了“id”,而不是用户和评论

Main File with Push Method带有推送方法的主文件

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)
    }
    })
    }
})
})

ObjectReferences user.js对象引用 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 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;

Main Form主窗体

    <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>

The only ID added to the user's database, not all comments and in the comment, collection data added perfectly添加到用户数据库的唯一ID,不是所有评论,在评论中,收藏数据完美添加

I think instead of using commentz use commentz._id and have a callback for .save .我认为不要使用commentz使用commentz._id并有一个.save回调。 It should work.它应该工作。

  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