Search code examples
node.jsejsmongoose-schema

Only half of mongoose schema being retrieved, although saved on database


I have a mongoose schema that seems to be working fine and saves or updates information correctly onto the database, however when trying to access the information, not all of it is being retrieved. The text property is missing.

Here is the schema:

var mongoose = require("mongoose");

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


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

This is how the comment is being retrieved (campground/show. The author of the comment is pulling through fine, but the text property is not showing as part of the comment object when I console.log

<% Campground.comments.forEach(function(comment){ %>

 <div>
    <p> <%= comment.author.username %> </p>
    <p> <%= comment.text %> </p>
</div>
<% } %>

The route where the Campground is passed in is below:

var express = require("express");
var router = express.Router({mergeParams: true});
var Campground = require("../models/campground");

router.get("/:id", function(req, res){
    Campground.findById(req.params.id).populate("comments", "author").exec(function(err, foundLoc){
        if(err){
            console.log(err);
        } else {
            res.render("campgrounds/show", {Campground: foundLoc});
        }
    });
});

Also when I am viewing the database on mongodb.com the schema is showing correctly and the text field is populated with the created data.

Below is what is showing up in the database

_id: ObjectId("5d720e6b71e33a05148676c7")
text: "THis is text!!!!"
__v:0
author: Object
   id:ObjectId("5d702a801d8f5e036de14042")
   username: "Bubbles"

And this is what I get when console.log(comment):

 author: { id: 5d702a801d8f5e036de14042, username: 'Bubbles' },
  _id: 5d7239e8c72e4d040ebbda1f }

For some reason text is no longer being retrieved.


Solution

  • You have selected only author field in commnets Model. If you need all fields of comments Model then use populate("comments") instead of populate("comments", "author").

    If Campground model has 2 referenced models, comments and author then

    Campground.findById(req.params.id).populate("comments").populate( "author").exec(function(err, foundLoc){
            if(err){
                console.log(err);
            } else {
                res.render("campgrounds/show", {Campground: foundLoc});
            }
        });
    

    You may like to have look documentation https://mongoosejs.com/docs/populate.html#populating-multiple-paths