我的aggregate函数使用postman重新填充空数组,但当我使用mongodbcompass执行相同操作时,它正确地返回了文档
我的发布路线是在mongodb compass中显示所有文档,但在postman中显示空数组我的aggregate函数使用postman重新填充空数组,但当我使用mongodbcompass执行相同操作时,它正确地返回了文档,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,我的发布路线是在mongodb compass中显示所有文档,但在postman中显示空数组 router.post("/dashboard/messages", async (req, res) => { try { const userid = req.body.userid; const user = await User.aggregate([ { "$match": { &
router.post("/dashboard/messages", async (req, res) => {
try {
const userid = req.body.userid;
const user = await User.aggregate([
{
"$match": {
"friendsList": userid
}
},
])
if(user){
res.send(user)
}else{
res.send({ message: "error" });
}
} catch (e) {
res.send({ message: "Error in Fetching user" });
}
});
聚合中的mongodb罗盘输入为
{
friendsList:ObjectId('6043100b0ca25c23d4928067')
}
输出匹配的文档
例如:
_
邮递员:
输入
输出:
[]
我认为正确的代码是
router.post('/dashboard/messages', async (req, res) => {
try {
const userid = req.body.userid;
const user = await User.aggregate([
{ $match: { friendsList: mongoose.Types.ObjectId(userId) } },
]);
if (user.length) {
res.send(user);
} else {
res.send({ message: 'error' });
}
} catch (e) {
res.send({ message: 'Error in Fetching user' });
}
});
首先需要将字符串转换为objectId,然后必须使用if(user.length)
而不是if(user)
因为
用户将始终是一个数组。您必须检查数组中是否有数据。这就是为什么我在if else
条件中使用user.length
。您必须将字符串userId转换为obejct id,您使用的是mongoose npm还是mongodb npm?mongoose如何使用friendsList:mongoose.Types.ObjectId(userId)
只需控制台catch块中的e.message
或e
。我猜,发布消息和errorPratik,正如你所说的FriendList是一个数组。仅为了匹配记录,等待User.aggregate([{“$match”:{“$expr”:{“$in”:[ObjectId(userId),“$friendLists”]}},]))
[]
router.post('/dashboard/messages', async (req, res) => {
try {
const userid = req.body.userid;
const user = await User.aggregate([
{ $match: { friendsList: mongoose.Types.ObjectId(userId) } },
]);
if (user.length) {
res.send(user);
} else {
res.send({ message: 'error' });
}
} catch (e) {
res.send({ message: 'Error in Fetching user' });
}
});