Home > Back-end >  Mongoose pushing only ObjectID, not the whole document
Mongoose pushing only ObjectID, not the whole document

Time:12-09

I have a recipe blog site, where every single recipe have comments. Every comments saving into the comments collection, but when i push the comments to the right recipe, than only saving the ObjectID. Here is my code:

Recipe model

const { Double } = require('bson');
const mongoose = require('mongoose');

const recipeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: 'This field is required.'
    },
    description: {
        type: String,
        required: 'This field is required.'
    },
    quantity: {
        type: Array,
        required: 'This field is required.'
    },
    ingredients: {
        type: Array,
        required: 'This field is required.'
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Comment'
        }
    ],
    recipe_id: {
        type: String,
    }

});

recipeSchema.index({ name: 'text', description: 'text' });
const Recipe = module.exports = mongoose.model('Recipe', recipeSchema);

Comment Model

const commentSchema = new mongoose.Schema({
    username: {
        type: String,
        required: 'This field is required.'
    },
    comment: {
        type: String,
        required: 'This field is required.'
    },
    recipe_id: {
        type: String
    }
});

Routes

router.get('/', recipeController.homepage);
router.get('/recipe/:id', recipeController.exploreRecipe );
router.get('/categories/:id', recipeController.exploreCategoriesById);
router.get('/categories', recipeController.exploreCategories);
router.get('/submit-recipe', recipeController.submitRecipe);
router.post('/submit-recipe', recipeController.submitRecipeOnPost);
router.post('/recipe/:id/comments', recipeController.CommentRecipeOnPost);

Controller

module.exports.CommentRecipeOnPost = async(req, res) => {
    const comment = new Comment({
      username: req.body.username,
      comment: req.body.comment
    });
    comment.save((err, result) => {
      if (err){
        console.log(err)
      }else {
        Recipe.findById(req.params.id, (err, post) =>{
          if(err){
            console.log(err);
          }else{
            post.comments.push(result);
            post.save();

            console.log('====comments=====')
            console.log(post.comments);
            res.redirect('/');
          }
        })
      }
    })
   }

I tried with populate and another methods, but no one worked, after a lots of hour programming i done with these, that i can save only the ObjectId-s.

CodePudding user response:

This's because you define comments at recipe schema as an ObjectId and that's right, if you want to get full comment parameters you will populate the record

const recipe = await Recipe.findOne({ _id: "recordId"}).populate("posts") 

this will return all comments details

{  name: "Fitness recipe", description: "Fitness recipe to loss 10kg in 10 days only", comments: [ {_id: "recordId", username: "Smith June", comment: "That's awesome"}]}

if you need to save the whole document as an array of objects, not just the id so you can make schema like that

const recipeSchema = new mongoose.Schema({
    name: {
        type: String,
        required: 'This field is required.'
    },
    description: {
        type: String,
        required: 'This field is required.'
    },
    quantity: {
        type: Array,
        required: 'This field is required.'
    },
    ingredients: {
        type: Array,
        required: 'This field is required.'
    },
    comments: [
        { username: String, comment: String }
    ],
    recipe_id: {
        type: String,
    }

})

and in this case, you won't have any relations, you can list recipe comments easily.

  • Related