mongodb - 使用 _id 查找不适用于聚合
问题描述
我是 mongodb 的初学者,我正在尝试在 node.js 应用程序中使用 mongoose 编写查询:
const objectIdValue = secondId.valueOf();
const existedRelation = await this.model.aggregate([
{ $match: { _id: firstId } },
{ $project: {
relations: {
$filter: {
input: '$links',
as: 'link',
cond: {
$and: [
{ $eq: ['$$link.target.entityId', `${objectIdValue}`] },
{ $eq: ['$$link.linkTypeId', linkTypeId] },
],
},
},
},
},
},
]);
console.log('existedRelation: ', existedRelation);
当我执行它时,我得到了这个结果:
existedRelation: []
我尝试使用 mongoShell 执行它:
db.tasks.aggregate([
{ $match:{ _id: ObjectId("5bbf5800be37394f38a9727e") }},
{
$project: {
relations:{
$filter:{
input: '$links',
as: "link",
cond: {
$and: [
{$eq:["$$link.target.entityId", '5bbf52eabe37394f38a97276']},
{$eq: ["$$link.linkTypeId", ObjectId("5bbf4bfcb075e03bd4a1b779")]}
]
}
}
}
}
}
我得到了我想要的结果。我犯了什么错误?
解决方案
Mongoose 不会强制String
转换为ObjectId
聚合函数。所以你必须使用猫鼬手动投射它。
var mongoose = require('mongoose')
const existedRelation = await this.model.aggregate([
{ "$match": { "_id": mongoose.Types.ObjectId(firstId) } },
{ "$project": {
"relations": {
"$filter": {
"input": "$links",
"as": "link",
"cond": {
"$and": [
{ "$eq": ["$$link.target.entityId", `${objectIdValue}`] },
{ "$eq": ["$$link.linkTypeId", linkTypeId] }
]
}
}
}
}}
])
推荐阅读
- android - 如何解决生成同名'Lad;' 当给定一个新的缩小名称错误Android时
- regex - 谷歌表格过滤器排除有条件的重复项
- git - 写库的时候,是不是应该把TypeScript生成的JavaScript文件放到gitignore里面?
- jquery - 如何将 c# DataTable 传递给 jquery DataTable
- c# - LINQ中的字符串排序
- asp.net - “如何修复‘实体类型的实例’无法跟踪,因为键值‘{TypeId: 1}’的另一个实例已被跟踪。
- java - 使用 Apache Commons 和 Java FTP 下载后 Word 文档无法打开
- hibernate - Spring Data JPA:保存在一次事务中在父母之间移动孩子的父母列表
- javascript - 单独注册和登录服务的处理错误
- android - 如何使用动态响应键解析 json