Home > Blockchain >  populating mongoose model not returning expected results
populating mongoose model not returning expected results

Time:06-27

I have two models user and places . both models have refs to each other . I'm trying to populate the place model so that when I remove place , the place get removed from places and also from places array of user model . Place from Place model is removed successfully but why it is not getting removed from places array of user model . what am I doing wrong ?

My Code :

Place Model


const mongoose = require("mongoose");

const schema = mongoose.Schema;

const placeSchema = new schema({
    title  : {type :String , required :true} ,
    description : {type :String , required :true} ,
    image : {type :String , required :true} ,
    address : {type :String , required :true} ,

    location : {
        lat: {type : Number , required : true} ,
        lng : {type :Number , required : true}
    } ,

    creator : {type :mongoose.Types.ObjectId , required :true , ref :"User"} 
});

module.exports = mongoose.model("Place" , placeSchema);

User Model


const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");

const schema = mongoose.Schema;

const userSchema = new schema({
    userName : {type : String , required : true} ,
    email : {type : String , required : true , unique:true} ,
    password : {type : String , required : true , minlength:6} ,
    image :{type : String , required : true} ,
    places : [{type : mongoose.Types.ObjectId , required : true , ref : "Place"}]
});

userSchema.plugin(uniqueValidator);

module.exports = mongoose.model("User" , userSchema);

api for deleting place and also deleting place from places array of the user model



const deletePlace=async(req, res , next)=>{
    const placeId = req.params.pid;
 
    let place ;

  try
  {
     place = await PLACE.findById(placeId).populate('creator');
  }

  catch(err)
  {
    const error = new Error("SOMETHING WENT WRONG , COULD NOT DELETE PLACE");
    error.code = 500;
    return next(error);
  }

  if(!place)
  {
    const error = new Error("NO PLACE FOUND WITH SUCH ID");
    error.code = 500;
    return next(error);
  }

  try 
  {
    const session = await mongoose.startSession();
    session.startTransaction();
    await PLACE.deleteOne({placeId});
    place.creator.places.pull(place);
    
  }

  catch(err)
  {
    const error = new Error("SOMETHING WENT WRONG , COULD NOT DELETE PLACE");
    error.code = 500;
    return next(error);
  }

  res.status(200).json({message: "PLACE DELETED"});
};

CodePudding user response:

After changing the creator object, you need to save it:

place.creator.places.pull(place);
await place.creator.save();
  • Related