Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Why MongoDB on Nodejs Shows Different Results

    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 461
    Answer it

    I want to add a comment object to an array in camps collection.

    When i console.log the array i find my added data.

    But then i check my data base, i find that the comments array is empty.

     

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


    This is the Camp Schema

        var campgroundSchema = new mongoose.Schema({
          name: String,
          img: String,
          description: String,
          comments: [
            {
              type: mongoose.Schema.Types.ObjectId,
              ref: "Comment"
            }
          ]
        });

    This is the Comment Schema

        var commentSchema = new mongoose.Schema({
          text: String,
          author: String
        });

 1 Answer(s)

  • Hi,

    The problem seems with the way you have implemented it. You should use `findByIdAndUpdate` method, instead of searching it first and then updating the comments subdocument. The solution goes as follows:-
     
    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 boolean Optional. If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.

    Some helpful links

    https://docs.mongodb.com/manual/reference/method/db.collection.update/index.html
    https://medium.com/stackfame/how-to-push-or-pop-items-into-mongodb-document-array-via-mongoose-in-node-js-express-js-91b7bbd0d218
Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: