如何解决如何将MongoDB查询从Node.js驱动程序格式转换为Mongoose格式
在使用Mongoose进行查询的语法方面,我将提供一些帮助。
我有一个查询,该查询可以使用MongoDB Node.js驱动程序从嵌套的对象ID数组中删除一个ObjectId来很好地运行:
let filter = { _id : new ObjectId('5f30b40839aab119f4b3e21d'),'groups._id': new ObjectId('5f3a23ec3680923d04ff970c') };
let update = { $pull: { "groups.$.students": new ObjectId('5f1a57a9d433f86ec0750c2c') }};
client.db('database').collection('collection').findOneAndUpdate(filter,update,function(err,res) {
if (err) console.log(err);
console.log(JSON.stringify(res,null,2));
client.close();
});
当我尝试使用Mongoose架构运行查询时,该查询不会从数组中删除ObjectId,但是不会引发任何错误:
let groupFilter = { _id: existingClassroom._id,'groups._id': groupId };
let groupUpdate = { $pull: { "groups.$.students": existingUser._id } };
await Classroom.findOneAndUpdate(groupFilter,groupUpdate,{new: true},async (err,doc) => {
if(err){
console.log(err);
}
});
猫鼬模式具有以下定义的这些字段的模式:
groups:[
{
students:[
mongoose.Schema.Types.ObjectId
],dateCreated: {
type: Date,default: Date.now
}
}
]
解决方法
您可以使用mongoose.Types.ObjectId
将字符串ID转换为对象ID,
let groupFilter = {
_id: mongoose.Types.ObjectId(existingClassroom._id),'groups._id': mongoose.Types.ObjectId(groupId)
};
let groupUpdate = {
$pull: {
"groups.$.students": mongoose.Types.ObjectId(existingUser._id)
}
};
await Classroom.findOneAndUpdate(groupFilter,groupUpdate,{ new: true },async (err,doc) => { if (err) { console.log(err); } }
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。