我想基于某个字段移除子模式的行,而模式在父模式的数组中。我试过下面的代码,但失败了。任何人解决这个问题 //代码详细信息 use_list是父模式,其中名为frr_list的数组字段将数组元素作为模式。我想基于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);
}
})
});
答案 0 :(得分:1)
据我所知,您可以删除frr_list数组的各个项目,如下所示:
我假设您将通过frr_id删除frr_list的各个项目(这是由mongoose生成的_id)
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
});