emisqwe emisqwe - 3 months ago 9
Javascript Question

Create array of items from mongodb - node js

Im new to mongodb and node js so please excuse me if this is very simple. So I have a schema:

var mongoose = require('mongoose');

var CatSchema = new mongoose.Schema({
cat_name: String,
cat_value: Number
});

module.exports = mongoose.model('Cat', CatSchema);


And when I add data to my dbs, it looks like this:

> db.cats.find()
{ "_id" : ObjectId("..."), "cat_name" : "test1", "__v" : 0, "cat_value" : 55 }
{ "_id" : ObjectId("..."), "cat_name" : "test2", "cat_value" : 24, "__v" : 0 }


I want to call the dbs and create an array of cat_names for each document in the collection.

So the final effects looks like this:

var cat_names = [test1, test2 ... ]


Any idea how to do this? I tried using the
foreach
loop,
db.collection('cats')
however I just cannot figure it out.

Answer

This works for me: var cat_names = [];

Cat.find(function(err, data){
    if(err){            
        console.log(err);
    }
    var stringify = JSON.stringify(data)
    content = JSON.parse(stringify);

    content.forEach(function(result){
        cat_names.push(result.cat_name);
    })

    console.log(cat_names);
})