繁体   English   中英

Express / MongoDb通过ID查找所有对象并将其保存到数组中

[英]Express / MongoDb find all objects by ID and save them to an array

我的monongodb模式如下所示:

let statSchema = new mongoose.Schema({
        title: String,
        statId: String,
        stats: {
            likeCount: Number,
            commentCount: Number
        }
    });

let MyStat = mongoose.model("MyStat", statSchema);

我正在寻找一种方法,可以从数据库中获取所有statId元素并将它们放在数组中。

稍后,我要遍历带有request (npm request)的数组,该request将使用statId并从API请求JSON,该API将更新每个对应statId所有stats (likeCount和commentCount)。

如果我在下面使用此代码:

MyStat.find({}, function(err, foundStats){
    if (err) throw err;
    console.log(foundStats);
  });

它会记录数据库中的所有元素,但我不知道如何仅访问“ statId”。

我正在尝试使用console.log(foundStats.linkId); 但它返回undefined

foundStats是您需要在其中循环的数组。

foundStats.forEach((element) => {
    console.log(element.statId);
});

如果要返回statId,请仅按以下方式使用它:

 MyStat.find({}, 'statId' , function(err, foundStats){
    if (err) throw err;
    console.log(foundStats);
  });

这里查看文档

您的statId将存储为“ _id”。 因此,如果您未明确更改或设置ID字段,则将在“ _id”中找到对象ID字段。

在这种情况下,您可以使用

MyStat.find({}, '_id', function(err, foundStats){
    if (err) throw err;
    console.log(foundStats);
});

在“ foundStats”中,您会找到所有统计信息的ID。

欲了解更多检查猫鼬MongoDB的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM