TEL:400-8793-956
当前位置:程序、服务器

为什么在Nodejs上使用MongoDB会显示不同的结果

提问者: 近期获赞: 浏览人数: 发布时间:2021-02-03 14:36:58

 问:我想向Camps集合中的数组添加一个注释对象。

 
当我console.log数组时,我找到了我添加的数据。
 
但是随后我检查了数据库,发现comments数组为空。
 
 
 
    app.post('/campgrounds/:id/comments', function(req, res){
      Camp.findById(req.params.id, function(err, campComm){
        if(err){
          console.log(err);
          res.redirect('/campgrounds');
        }else{
          Comment.create(req.body.comment, function(err, comm){
            if(err){
              console.log(err);
            }else{
              campComm.comments.push(comm);
              console.log(campComm.comments);
              console.log(comm);
              campComm.save();
              console.log(campComm.comments);
              res.redirect("/campgrounds/" + campComm._id);
            }
          });
        }
      });
    });
 
 
这是营地模式
 
    var campgroundSchema = new mongoose.Schema({
      name: String,
      img: String,
      description: String,
      comments: [
        {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Comment"
        }
      ]
    });
 
这是评论模式
 
    var commentSchema = new mongoose.Schema({
      text: String,
      author: String
    });
 
 
答:问题似乎出在您实施它的方式上。您应该使用`findByIdAndUpdate`方法,而不是先搜索然后更新注释子文档。解决方案如下:
 
Camp.findByIdAndUpdate(
  id,
  {$push: {"comments.type": req.body.comments.type}},
  {safe: true, upsert: false},
  function(err, model) {
   if(err)
    console.log('error occured!')
   console.log('Saved successfully..');
  }
);
upsert 布尔值 可选的。如果设置为 true,则在没有文档符合查询条件时创建一个新文档。默认值为 false, 如果找不到匹配项, 则不插入新文档。
上一篇: 如何从Android Webview进行视频投射
下一篇: 可以为实时跟踪应用程序提供Android教程或资源链接吗?