【问题标题】:Mongoose: push a string into arrayMongoose:将字符串推入数组
【发布时间】:2021-10-11 23:25:15
【问题描述】:

我有一个网站,任何已登录的用户都可以在该网站上对商店发表评论。

所以基本上我有两个模式:

const journalSchema = new mongoose.Schema({
  title: String,
  category: String,
  subcategory: String,
  rating: Number,
  review: [{type: String}],
  link: String,
  description: String,
});


const userSchema = new mongoose.Schema ({
  username: String,
  password: String,
  journal: [{type: mongoose.Schema.Types.ObjectId, ref: 'Journal'}]
});



const Journal = mongoose.model("Journal", journalSchema);
const User = mongoose.model("User", userSchema);

来自 ejs 文件的表单:

  <div class="container my-3">
    <h1>Compose</h1>
    <form class="" action="/stats" method="post">
      <div class="form-group">

        <label for="review">Description</label>
        <textarea id="review" class="form-control" name="journalReview" rows="5" cols="30"></textarea>
      </div>
      <button class="btn btn-primary my-2" type="submit" name="button">Publish</button>
    </form>
  </div>

发布路线:

app.post("/stats", function(req, res){

  if(req.isAuthenticated()){
    const favJournal = req.body.savedJournal;
    const userId = req.user.id;
    const userReview = req.body.journalReview;

    User.findById(userId, function(err, foundUser){
    Journal.findById(favJournal, function(err, foundJournal){

      if(err){
        console.log(err);
      }


      else{
        if(foundUser){
          foundJournal.review.push(userReview);
          foundJournal.save(function(){
            console.log(foundJournal);
          });
          foundUser.journal.addToSet(foundJournal);
          foundUser.save(function(){
            res.redirect("/favourite");
          });
        }


        }


    });

    })
    .populate('journal')
    .exec(function(err, user){
      if(err) return handleError(err);
    });
  }

  else{
    res.redirect("/login");
  }

});

每次我尝试从 ejs 文件推送评论时,我都会收到此错误:

events.js:353
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'review' of null
    at C:\Users\HelloThere\Desktop\miesto\app.js:337:24
    at C:\Users\HelloThere\Desktop\miesto\node_modules\mongoose\lib\model.js:5065:18
    at processTicksAndRejections (internal/process/task_queues.js:77:11)
Emitted 'error' event on Function instance at:
    at C:\Users\HelloThere\Desktop\miesto\node_modules\mongoose\lib\model.js:5067:15
    at processTicksAndRejections (internal/process/task_queues.js:77:11)

我尝试了类似帖子的不同解决方案。类似于 mongoose 方法:findOneAndUpdate 和 updateOne,但它们只是返回 null。

【问题讨论】:

  • 您是否尝试打印变量 foundJournal?我不认为这是与猫鼬相关的问题,您正在尝试将其推入空值。
  • 是的,经过一些检查,这似乎是问题所在。问题是我不知道如何从 ejs 文件中获取商店的 id。我试过 req.journal.id 但我得到 id is undefined.

标签: node.js mongodb mongoose ejs


【解决方案1】:

我想我找到了问题的原因,我的 ejs 文件中有两个 post 表单,并且由于两个表单都有提交按钮,没有任何区别,所以只有第一个表单在 post 路由中被调用。

【讨论】:

    【解决方案2】:

    您可以通过findOneAnUpdate$push 运算符来实现此目的,而不是获取商店并使用JavaScript 代码对其进行操作然后将其保存回数据库。 比如这个查询

    Shop.findById( shopId, (shop) => {
      shop.products.push(product);
      shop.save();
    }
    

    可以通过这个查询来完成

    Shop.findOneAndUpdate(
       { _id: shopId }, 
       { $push: { 
                 products: product
               } 
       })
    

    $pop$push$pull 是在 Mongoose 中操作数组的非常强大的工具。查看文档。

    对于您遇到的错误,我认为您收到错误是因为您将错误的journalId 传递给 findById。如果您确实有具有该 ID favJournal 的文档,请与 MongoDB Compass 联系

    【讨论】:

    • 谢谢,是的,你是对的,问题在于商店的 ID。有没有办法从 ejs 文件中获取模式的 id?我试过 req.journal.id 但没用。
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2018-02-21
    • 2021-08-18
    相关资源
    最近更新 更多