mamadgi aishwarya
mamadgi aishwarya

Reputation: 107

Adding object Id to an array of object Ids

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("/");
})

Upvotes: 0

Views: 1299

Answers (1)

Rohit Ambre
Rohit Ambre

Reputation: 961

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

Upvotes: 2

Related Questions