简体   繁体   中英

Reading object's properties from MongoDB via mongoose

i have basic thing to do, yet it doesn't work. I have following mongoDB: (collection fruits):

{ "_id" : ObjectId("5f4d0d1f4e31f73410733d8b"), "name" : "Banana", "cost" : 4, "stock" : 50, "__v" : 0 }    
{ "_id" : ObjectId("5f4d0d1f4e31f73410733d8c"), "name" : "Pineapple", "cost" : 12, "stock" : 30, "__v" : 0 }
{ "_id" : ObjectId("5f4d0d1f4e31f73410733d8d"), "name" : "Apple", "cost" : 2, "stock" : 100, "__v" : 0 }

,and following code:

let scheme = new mongoose.Schema({});
let ovoce = mongoose.model("Fruits",scheme);

So, it's easy to read. Just call ovoce.find() (which returns the correct array). However, when i try to pick name for each and display it, the console logs undefined:

ovoce.find({}, function(err,res){
    if(err){
        console.log(err);
    } else {//the res contains the array with all the fruits
        res.forEach(function(fruit){
            console.log(fruit.name);
        });
    }
});

I have no idea what i'm doing wrong. Help very much appreciated.

Maybe element of array need be parse before console.log? Log whole fruit and see output (or/and upload here).

Nvm, i figured it out. I forgot to put ; at the ond of the code. For some reason the program stopped in last callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM