簡體   English   中英

填充貓鼬模型未返回預期結果

[英]populating mongoose model not returning expected results

我有兩個模型 user 和 places 。 兩個模型都互相引用。 我正在嘗試填充 place 模型,以便當我刪除 place 時,該位置會從 places 以及用戶模型的 places 數組中刪除。 Place from Place 模型已成功刪除,但為什么它沒有從用戶模型的 places 數組中刪除。 我究竟做錯了什么 ?

我的代碼:

放置模型


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);

用戶模型


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



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

更改創建者對象后,您需要保存它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM