Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Express/MongoDb按ID查找所有对象并将其保存到数组中_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

Node.js Express/MongoDb按ID查找所有对象并将其保存到数组中

Node.js Express/MongoDb按ID查找所有对象并将其保存到数组中,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我的monongodb模式如下所示: let statSchema = new mongoose.Schema({ title: String, statId: String, stats: { likeCount: Number, commentCount: Number } }); let MyStat = mongoose.model("MyStat", statSch

我的monongodb模式如下所示:

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

let MyStat = mongoose.model("MyStat", statSchema);
 MyStat.find({}, 'statId' , function(err, foundStats){
    if (err) throw err;
    console.log(foundStats);
  });
我正在寻找一种方法,可以从数据库中获取所有statId元素,并将它们放入一个数组中

稍后,我将使用request npm request遍历该数组,该数组将获取statId,并从API请求JSON,该API将更新每个对应statId的所有statslikecoount和commentCount

如果我使用以下代码:

MyStat.find({}, function(err, foundStats){
    if (err) throw err;
    console.log(foundStats);
  });
它将记录我数据库中的所有元素,但我不知道如何访问“statId”


我试图使用console.logfoundStats.linkId;但是它返回的是未定义的。

foundStats是一个数组,您需要在其中循环

foundStats.forEach((element) => {
    console.log(element.statId);
});
如果要返回statId,请按如下方式使用:

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

let MyStat = mongoose.model("MyStat", statSchema);
 MyStat.find({}, 'statId' , function(err, foundStats){
    if (err) throw err;
    console.log(foundStats);
  });

请参阅文档

您的statId存储为'\u id'。因此,如果不显式更改或设置id字段,则对象id字段将位于“\u id”中

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

MyStat.find({}, '_id', function(err, foundStats){
    if (err) throw err;
    console.log(foundStats);
});
在“foundStats”中,您将找到统计信息的所有id

有关更多信息,请检查的可能重复项