[英]Mongoose search query with regex not returning expected results with multiple conditions and population
[英]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.