Search code examples
javascriptstrapi

I'm using strapi to build an API but findone returns always {}


This is my code

console.log(JSON.stringify(receivedProduct));
var dbProduct = strapi.query('product').findOne({ wooSku: receivedProduct.sku });
console.log(JSON.stringify(dbProduct));

receivedProduct Output:

{
...some json...
"sku": "LUPV-03300-1",
...some json...
}

dbProduct output:

{}

If I check in the admin, there already exists a product with this attribute value: enter image description here

What could be wrong?

###############################

UPDATE:

As it returns a promise, it solved using .then() ... But I dont't understand why is it "undefined" after adding a function call

var dbProduct = strapi.query('product').findOne({ wooSku: receivedProduct.sku })
.then(dbProduct => { 
   console.log(JSON.stringify(dbProduct)); 
   saveProductIfNotExists(receivedProduct);} 
); 

Solution

  • My first guess is that you receive an pending promise because this looks like an async task. Then i have took a look at this last example where they use await https://strapi.io/documentation/3.0.0-beta.x/concepts/queries.html#custom-queries and yes thats probably an promise. You can try this:

    console.log(JSON.stringify(receivedProduct));
    var dbProduct = strapi.query('product').findOne({ wooSku: receivedProduct.sku }).then(dbProduct => {
       console.log(JSON.stringify(dbProduct));
    });