Mongoose: Schema referencing stores the whole value instead of ObjectId alone

Created on 26 Jan 2018  路  4Comments  路  Source: Automattic/mongoose

Lately, I've been going through a course named The Web Developer Course.
In which the final project is based on Camps.
In the project, the comment database and the campground database are referenced, that is, the ObjectIds of the comments which are posted in a campground is stored in an array. This is what to be happened actually.

But in my case, the exact scenario's changed..When I try to Add a new comment what actually happens is that the total object gets stored in the comments array instead of the ObjectId of the comment.
I've almost gone through Stackoverflow seeking solution for my problem but failed.

I just wanted the ObjectId to be stored in the comments array instead it stores the whole Object which brings me problem in updating and deleting a comment. When I delete or update a comment the operation does happen in the Comments database but doesn't reflect in the Campgrounds database. Please help me with this issue. If anyone's taking the same course, Please give me solutions if you've experienced something like this already. The Schema are as given below

Campground Schema:

var mongoose = require("mongoose");

var campgroundSchema = mongoose.Schema({
    campGroundName: String,
    campGroundImage: String,
    description: String,
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Comment"
        }    
    ],
    addedBy: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

module.exports = mongoose.model("Campground", campgroundSchema);

Comment Schema:

var mongoose = require("mongoose");

var commentSchema = mongoose.Schema({
    text: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

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

Post request for creating a comment:

router.post("/", middleware.isLoggedIn, function(req, res) {
    Comment.create(req.body.comment, function(err, createdComment) {
          if(err) {
              console.log(err);
          } else {
              createdComment.author.id = req.user._id;
              createdComment.author.username = req.user.username;
              createdComment.save();                  Campground.findById(req.params.id).populate("comments").exec(function(err, foundCampground){
              foundCampground.comments.push(createdComment);
              foundCampground.save();
              req.flash("success" , "Comment created successfully");
              res.redirect("/index/" + req.params.id); 
             });
          }        
    });
});

The whole source code is below,

https://1drv.ms/u/s!AmISAco3PGaPhQl_Riu8nroCom5h

NodeJS : v6.11.4
NPM: v6.11.4
Mongoose: v5.0.0-rc2

Please help me fix this issue!

confirmed-bug

Most helpful comment

Yeah! it worked.. Thanks 馃挴

All 4 comments

Confirmed bug in 5.0.0. Below script demonstrates the issue

var mongoose = require('mongoose');

mongoose.set('debug', true);
mongoose.connect('mongodb://localhost:27017/test');

var mongoose = require("mongoose");

var campgroundSchema = mongoose.Schema({
    campGroundName: String,
    campGroundImage: String,
    description: String,
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Comment"
        }    
    ],
    addedBy: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

var Campground = mongoose.model("Campground", campgroundSchema);

var commentSchema = mongoose.Schema({
    text: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

var Campground = mongoose.model("Campground", campgroundSchema);

var commentSchema = mongoose.Schema({
    text: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

var Comment = mongoose.model("Comment", commentSchema);

var userId = new mongoose.Types.ObjectId();

Campground.create({ campGroundName: 'test' }, function(error, campground) {
  Comment.create({ text: 'test' }, function(err, createdComment) {
    if (err) {
      return console.log(err);
    }
    createdComment.author.id = userId;
    createdComment.author.username = 'test';
    createdComment.save();
    Campground.findById(campground).populate("comments").exec(function(err, foundCampground){
      foundCampground.comments.push(createdComment);
      foundCampground.save(function(error, doc) {
        Campground.findById(campground).exec(function(error, campground) {
          console.log(campground);
        });
      });
    });
  });
});
$ node gh-6048.js 
Mongoose: campgrounds.insert({ comments: [], _id: ObjectId("5a70b3196944120ed8f658e0"), campGroundName: 'test', __v: 0 })
Mongoose: comments.insert({ _id: ObjectId("5a70b3196944120ed8f658e1"), text: 'test', __v: 0 })
Mongoose: campgrounds.findOne({ _id: ObjectId("5a70b3196944120ed8f658e0") }, { fields: {} })
Mongoose: comments.update({ _id: ObjectId("5a70b3196944120ed8f658e1") }, { '$set': { 'author.id': ObjectId("5a70b3196944120ed8f658df"), 'author.username': 'test' } })
Mongoose: campgrounds.update({ _id: ObjectId("5a70b3196944120ed8f658e0") }, { '$push': { comments: { '$each': [ { author: { id: ObjectId("5a70b3196944120ed8f658df"), username: 'test' }, _id: ObjectId("5a70b3196944120ed8f658e1"), text: 'test', __v: 0 } ] } }, '$inc': { __v: 1 } })
Mongoose: campgrounds.findOne({ _id: ObjectId("5a70b3196944120ed8f658e0") }, { fields: {} })
{ comments: [],
  _id: 5a70b3196944120ed8f658e0,
  campGroundName: 'test',
  __v: 1 }
^C
$ 

Is this bug fixed?

@Blackdeathanton if you want to test out the change before 5.0.3 is released into the wild you can download the newer version here
I was curious and tested it out:
before:

Help: ./6048.js 
Mongoose: campgrounds.insert({ comments: [], _id: ObjectId("5a7336041b3ea8e0dd62a092"), campGroundName: 'test', __v: 0 })
Mongoose: comments.insert({ _id: ObjectId("5a7336051b3ea8e0dd62a093"), text: 'test', __v: 0 })
Mongoose: campgrounds.findOne({ _id: ObjectId("5a7336041b3ea8e0dd62a092") }, { fields: {} })
Mongoose: comments.update({ _id: ObjectId("5a7336051b3ea8e0dd62a093") }, { '$set': { 'author.id': ObjectId("5a7336041b3ea8e0dd62a091"), 'author.username': 'test' } })
Mongoose: campgrounds.update({ _id: ObjectId("5a7336041b3ea8e0dd62a092") }, { '$push': { comments: { '$each': [ { author: { id: ObjectId("5a7336041b3ea8e0dd62a091"), username: 'test' }, _id: ObjectId("5a7336051b3ea8e0dd62a093"), text: 'test', __v: 0 } ] } }, '$inc': { __v: 1 } })
Mongoose: campgrounds.findOne({ _id: ObjectId("5a7336041b3ea8e0dd62a092") }, { fields: {} })
{ comments: [],
  _id: 5a7336041b3ea8e0dd62a092,
  campGroundName: 'test',
  __v: 1 }

after:

Help: ./6048.js 
Mongoose: campgrounds.insert({ comments: [], _id: ObjectId("5a735620c49529e41b4d3c98"), campGroundName: 'test', __v: 0 })
Mongoose: comments.insert({ _id: ObjectId("5a735620c49529e41b4d3c99"), text: 'test', __v: 0 })
Mongoose: campgrounds.findOne({ _id: ObjectId("5a735620c49529e41b4d3c98") }, { fields: {} })
Mongoose: comments.update({ _id: ObjectId("5a735620c49529e41b4d3c99") }, { '$set': { 'author.id': ObjectId("5a735620c49529e41b4d3c97"), 'author.username': 'test' } })
Mongoose: campgrounds.update({ _id: ObjectId("5a735620c49529e41b4d3c98") }, { '$push': { comments: { '$each': [ ObjectId("5a735620c49529e41b4d3c99") ] } }, '$inc': { __v: 1 } })
Mongoose: campgrounds.findOne({ _id: ObjectId("5a735620c49529e41b4d3c98") }, { fields: {} })
{ comments: [ 5a735620c49529e41b4d3c99 ],
  _id: 5a735620c49529e41b4d3c98,
  campGroundName: 'test',
  __v: 1 }

It turns out that the 5.0.3 tag was published to npm last night though, so installing the @latest version from npm will also get it for you.

Yeah! it worked.. Thanks 馃挴

Was this page helpful?
0 / 5 - 0 ratings