i want to remove the child schema's row based on certain field and schema is inside the array of parent schema. i have tried with below code but failed.can any one resolve this //code details use_list is parent schema in which its array field called frr_list has array element as schemas . and i want to remove individual row of that child schema based on fren_id. //
//main parent schema var user_list = new Schema({ user_id: { type: mongoose.Schema.Types.ObjectId, ref: 'user_reg' }, fren_list: [fren_list], block_list: [fren_block_list], frr_list: [fern_req_recieved_list], //asking about this array frs_list: [fern_req_sent_list], }); //child schema var fern_req_recieved_list = new Schema({ //fren req list fren_id: { type: mongoose.Schema.Types.ObjectId, ref: 'user_reg' }, fren_name: String, dt: { type: Date, default: Date.now }, status: { type: String, default: "pending" } //pending, rejected,accepted }); User.list.findOne({ //parent document user_id: currentUserId }, function(err, user) { ///below is child inside the array field and is schema user.frr_list.findOneAndRemove({ fren_id: requestedUserId }, function(err, message) { if (err) { callback(null, false); } else { callback(null, true); } }) });
As I understand you can delete the individual items of frr_list array like this:
I assume that you will be deleting the individual items of frr_list by frr_id (which is _id which is generated by mongoose)
User.update({ _id: userListId, user_id:currentUserId //filter record by userListId and currentUserId },
{ //now pull the required row from the array based on _id of array
$pull: { frr_list: { _id: frr_id } } },
function(err,result){
if(result.ok==1 && result.nModified==1 && result.n==1)
//successfully deleted
else if(result.ok==1 && result.nModified==0 && result.n==0)
//no record exist
else
//something goes wrong
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.