Mongoose TypeScript 聚合:在类型“任何 []”上不存在
Posted
技术标签:
【中文标题】Mongoose TypeScript 聚合:在类型“任何 []”上不存在【英文标题】:Mongoose TypeScript Aggregation: does not exist on type 'any[]' 【发布时间】:2020-04-23 05:35:49 【问题描述】:我正在尝试将常规 mongo 调用换成聚合调用。原来的工作是..
const account = await userModel
.findOne( 'shared.username': username )
.exec();
console.log(account._id)
新的聚合函数是……
const account = await userModel.aggregate([
$match:
'shared.username': username,
,
,
$lookup:
as: 'photos',
foreignField: 'userId',
from: 'photos',
localField: '_id',
,
,
]);
console.log(account._id)
// ^ Error
我得到的错误是
Property '_id' does not exist on type 'any[]'.ts(2339)
我确定他们是 _id 被返回,因为我可以在 Studio 3T 聚合输出中看到它
"_id" : ObjectId("5e10983cb182628af48e590a"),
"shared" :
"currency" : "USD",
"followers" : 0,
"following" : 0,
"language" : "en",
"loggedIn" : true,
"twofactor" : false,
"warningMessage" : "verify",
"email" : "email@gmail.com",
"fullName" : "James",
"username" : "57fe31142e10",
"location" : "/57fe31142e10"
,
"photos" : [
"_id" : ObjectId("5e117b8f227a32597cdcbb6e"),
"category" : "Double Deckers",
"previewId" : "5e10983cb182628af48e590a/0f5d0010a4e55794419c03328184cfb45984bf43.jpg",
"published" : true,
"thumbnailId" : "5e10983cb182628af48e590a/54265d07a962f8544a9ebdc1d876775d9eeed471.jpg",
"userId" : ObjectId("5e10983cb182628af48e590a"),
"zoomId" : "5e10983cb182628af48e590a/fe0b2016a0be2b26259aaf5152ef22edfffa0c57.jpg",
"createdAt" : ISODate("2020-01-05T06:00:47.756+0000"),
"updatedAt" : ISODate("2020-01-05T06:00:47.756+0000"),
"__v" : 0
,
"_id" : ObjectId("5e11ab2f0f451779f70f89b1"),
"category" : "Single Decker",
"previewId" : "5e10983cb182628af48e590a/30d496e44faae1345e4c555accfdc6446fd11945.jpg",
"published" : true,
"thumbnailId" : "5e10983cb182628af48e590a/9293dd5517f694341a2e582df670dc9bbaba0763.jpg",
"userId" : ObjectId("5e10983cb182628af48e590a"),
"zoomId" : "5e10983cb182628af48e590a/0a038434e857b05ef8aa46da6dab01259ba2b03e.jpg",
"createdAt" : ISODate("2020-01-05T09:23:59.007+0000"),
"updatedAt" : ISODate("2020-01-05T09:23:59.007+0000"),
"__v" : 0
,
"_id" : ObjectId("5e11aba00f451779f70f89b2"),
"category" : "Midi",
"previewId" : "5e10983cb182628af48e590a/2267d14aa642d6cee86319909177ce4eef45cbcc.jpg",
"published" : true,
"thumbnailId" : "5e10983cb182628af48e590a/9d006f1ed361540ecf9d24c807a111770cf9e44f.jpg",
"userId" : ObjectId("5e10983cb182628af48e590a"),
"zoomId" : "5e10983cb182628af48e590a/88a87440a9b7845aa44c72411edddc98ea56f6b9.jpg",
"createdAt" : ISODate("2020-01-05T09:25:52.019+0000"),
"updatedAt" : ISODate("2020-01-05T09:25:52.019+0000"),
"__v" : 0
]
【问题讨论】:
【参考方案1】:错误是正确的,aggregation
输出的是一个对象数组。
你想做:(假设聚合返回结果)
console.log(account[0]._id)
【讨论】:
以上是关于Mongoose TypeScript 聚合:在类型“任何 []”上不存在的主要内容,如果未能解决你的问题,请参考以下文章
使用 Typescript 从 Mongoose 模型访问文档属性
typescript 使用TypeScript和MongoDb的Mongoose示例
typescript 使用TypeScript和MongoDb的Mongoose示例