0

So... I basically search an item in the database, find it, print it fine but I can t access the attributes. When I try to print them they show undefined.

I know that the attribute are in fact undefined because it doesn t break the loop and I do have both attributes in my mongoose schema. I also tried to stringify and parse it to json back and didn t work. (this is all the material I could find)

This is the script:

const name_to_find = 'Copac';

async function myFetch(){

    const express = require('express');
    const mongoose = require('mongoose');
    const Item = require('./models/Item');
    const mongoUrl = process.env.MONGO_URL;
    const appsc = express();

    var connectWithRetry = function() {
        return mongoose.connect(mongoUrl, { useNewUrlParser: true,  useUnifiedTopology: true }, function(err) {
            if (err) {
                console.error('Failed to connect to mongo on startup - retrying in 3 sec', err);
                setTimeout(connectWithRetry, 3000);
            }
        });
    };
    connectWithRetry();

    var date1 = new Date();

    while(true){

        var date2 = new Date();

        if(date1.getTime() - date2.getTime() > 100000)
            break;
        try {
            const response = await Item.find({name: name_to_find});
            var mergi = JSON.parse(JSON.stringify(response));// doesn t work
            
            //if (response['status'] == 1)
            if(response.status == 1){
                console.log("200");
                break;
            }
            else {
                console.log(JSON.stringify(response));
                console.log(response.status);
                console.log(mergi.name);
            }
            
        }
        catch (err) {
            console.error(err);
            console.log(name_to_find);
        }
    }

}
myFetch();

this is the schema:

const mongoose = require('mongoose');         
const Schema = mongoose.Schema;                 

const ItemSchema = new Schema({                 
  status: {                       
    type: Number,                          
    required: true                             
  },                       
  name: {                           
    type: String,                            
    required: true                
  }                       
});                    

module.exports = Item = mongoose.model('item', ItemSchema);

and this is the output:

[{"_id":"60fc235414d05a001a5fa630","status":1,"name":"Copac","__v":0}] undefined undefined

As u see, it is indeed 1 and should exit the loop but it doesn t.

nothing here helped either link.

Ole Pannier
  • 3,208
  • 9
  • 22
  • 33

1 Answers1

0

Ok so the problem was that mongoose treats the result of .find() function as an array and I should have casted it with results[0] or use .findOne(). I chose the former. The answer was actually in the link provided but u have to scroll a bit for it. Tell me if u want me to delete this