0

My monongodb schema looks like this:

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

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

I am looking for a way where I can get all the statId elements from the database and put them in an array.

Later on I want to go through that array with request (npm request) that will take the statId and request JSON from API that will update all stats(likeCount and commentCount) for each corresponding statId.

If I use this code below:

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

it will log all the elements in my database but I don't know how to access just 'statId'.

I was trying to use console.log(foundStats.linkId);but it returns undefined.

Bager
  • 3
  • 2
  • Possible duplicate of [Mongoose, Select a specific field with find](https://stackoverflow.com/questions/24348437/mongoose-select-a-specific-field-with-find) – Dan O Oct 21 '18 at 22:16

2 Answers2

1

foundStats is an array you need to loop in them.

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

if you want to return the statId only use it like this:

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

see the docs here

Tarek Essam
  • 3,602
  • 2
  • 12
  • 21
0

Your statId is stored as '_id'. So If you do not explicitly change or set id field, the object id field will be found in '_id'.

In this case, you might use

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

In the 'foundStats' you will find all the id of the stats.

For more check the mongoose, mongoDB

Shams Nahid
  • 6,239
  • 8
  • 28
  • 39