Search code examples
javascriptmongoose

How to Return Just the Value of the first Document in MongoDB without knowing the Query Filter


I am trying to extract the value of a field by appending that field’s name to my query when using findOne()

My mongoose collection called products:

{ "_id" : 1, "product" : "Bat", "sizes" : [ "S", "M", "L" ] }
{ "_id" : 2, "product" : "Hat", "sizes" : [ "S", "L", "XL" ] }
{ "_id" : 3, "product" : "Cap", "sizes" : [ "M", "L" ] }

Here is my javascript (simplified):

app.post("/", async function(req, res){

const product = await products.findOne().product;
console.log(product);

});

I am expecting Bat to return, but instead I get undefined.

(edited) Hi all, I'm looking as if I don't know what the query filter is. My real code is looking to take the first document and rerun it through an API to update the information, delete the first document, and create a new one in my database. I want this code to run all the way through my database so the first document will change each time.

So in this example, it would go from Bat to Hat to Cap that I would need to run through my API.

Sorry I wasn't clear. I was trying to keep the question simple.


Solution

  • Okay, so this is what I ended up doing. I used a for loop to run through my distinct array. I'll likely put a setInterval so I don't max out the API.

    app.post("/", async function(req, res){
    
    for (var i=0; i<products.length; i++) {
    
    const data = await products.distinct("product");
    const product = data[i];
    
    console.log(product);
    }
    
    });