0

Even after I add post._id to user posts array, the posts array is still empty. Please help me find the error. I want to populate the posts array later using the object Id.

User.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var User = new Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    email:{
        type: String,
        required: true
    },
    password:  {
        type: String,
        required: true
    },
    posts:[{
        type :mongoose.Schema.Types.ObjectId, 
        ref: 'Post'
    }]
});
 
module.exports = mongoose.model('User', User);

Post.js

const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/PostsDB",{useNewUrlParser:true, useUnifiedTopology: true});
const PostSchema={
Title:String,
Content:String,
Author:{
    type:mongoose.Schema.Types.ObjectId,
    ref: 'User'
}
};
const Post=mongoose.model("Post",PostSchema);
module.exports=Post;

app.js

app.post("/compose",function(req,res){
  const post=new Post({
    Title:req.body.postTitle,
    Content:req.body.postBody,
    Author:req.user._id
    });
    post.save();
    User.findOne({_id:req.user._id}).then(function(result,err){
      console.log(result);
      console.log(typeof post._id);
      result.posts.push(post._id);
    }).catch(err=>{console.log(err);});
    res.redirect("/");
})

1 Answer 1

2

You are just pushing id into the array but you are not saving it back again into the the DB. so once you pushed the id, make use save function to save updated value or you can use update query like mongoose update

app.post("/compose",function(req,res){
  const post=new Post({
    Title:req.body.postTitle,
    Content:req.body.postBody,
    Author:req.user._id
    });
    post.save();
    User.findOne({_id:req.user._id})
      .then(function(err, result){
         console.log(result);
         console.log(typeof post._id);
         result.posts.push(post._id);
         result.save();   //<------- added save method call
      })
      .catch(err=>{console.log(err);});
    res.redirect("/");
})

Also as a suggestion, use err as a first argument in callback function

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.