gpt4 book ai didi

node.js - Mongoose id 函数返回 null

转载 作者:可可西里 更新时间:2023-11-01 10:28:42 25 4
gpt4 key购买 nike

我正在尝试从 MongoDB 获取子文档。我可以获得父文档,如下所示:

    {
"_id" : ObjectId("5550a7948be994430f7df1b4"),
"address" : "Grafton St, Dublin 2",
"coords" : [
-6.2597468,
53.3422998
],
"facilities" : [
"food",
"irish history"
],
"name" : "Laura Dunphy",
"openingTimes" : [
{
"days" : "Monday - Friday",
"times" : [
"10am",
"12pm",
"2pm"
]
},
{
"days" : "Saturday",
"times" : [
"8am",
"10am",
"12pm"
]
}
],
"rating" : 3,
"reviews" : [
{
"author" : "Simon Holmes",
"id" : ObjectId("5550c26e8c334adebc7c5dc3"),
"rating" : 5,
"timestamp" : ISODate("2013-07-15T23:00:00Z"),
"reviewText" : "Great guide, it was fun."
}
]
}

当我这样做时:

console.log('guide.reviews is ');
console.log(guide.reviews);

我明白了:

guide.reviews is 
[{ id: 5550c26e8c334adebc7c5dc3,
rating: 5,
timestamp: Tue Jul 16 2013 00:00:00 GMT+0100 (IST),
reviewText: 'Great guide, it was fun.',
createdOn: Fri May 15 2015 18:20:57 GMT+0100 (IST),
author: 'Simon Holmes' }]

这很好。但是当我尝试使用 Mongoose id 函数获取评论时,我总是返回 null:

review = guide.reviews.id('5550c26e8c334adebc7c5dc3');

console.log('review is ');
console.log(review);

结果:

review is
null

知道我做错了什么吗?

最佳答案

MongooseDocumentArray.id(id)方法在文档数组中搜索 _id 属性,但您的子文档没有 _id 属性,而是具有 id。您要么必须将其更改为 _id,要么使用普通的旧 .filter() 或类似的解决方法。

关于node.js - Mongoose id 函数返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30265446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com