Vikash Kumar
Vikash Kumar

Reputation: 1111

How to print mongoose find() array docs in console

I'm trying to use mongodb with node.js using Mongoose ODM.

I've written some sample code which is given below:

Sample Code -

/*!
 * mongoose.js
 * 
 * Getting Started
 */ 

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

var db = mongoose.connect('mongodb://localhost/trymongo').connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to database");  // we're connected!
  
  // create schemas
  var SubjectSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    teacher: {
        type: String
    }
  },
  {
    collection: 'subjects'
  });

  // create a model
  var Subject = mongoose.model('Subject', SubjectSchema);
  
  var arr = [{ name: 'Computer Programming', teacher: 'M. Swaminathan' }, { name: 'History' }];
  Subject.insertMany(arr, function(err) {
    if (err) throw err;
    
    console.log('Multiple subjects created!');

    // get all the subjects
    Subject.find({}, function(err, subjects) {
        if (err) throw err;
                
        console.log(subjects);
    });
  });
});

I want to print subjects in console using console.log() returned by mongoose model but it only prints like this -

[ [object Object], [object Object] ]

I've also tried with console.dir() but result is same as above.

Upvotes: 2

Views: 6718

Answers (3)

armusiq
armusiq

Reputation: 1

just in case for those who are struggling to console log only the names of the fruits :

  Fruit.find()
  .then((fruits) => {
    fruits.forEach((fruits) => {
      console.log('Names of fruits:', fruits.name);
    });
  })
  .catch((error) => {
    console.error('Error retrieving documents:', error);
  }).finally(()=> {
    mongoose.connection.close();
  }); 

Upvotes: 0

qolu
qolu

Reputation: 1

I've just started learning Mongoose and found this question while facing the same problem now over 7 years after it was originally posted. I was finally able to figure out how to print the docs queried by a .find() to terminal for Mongoose version 7.0, which probably isn't helpful in regards to the original post, but I figured I would share for the benefit of anyone stumbling upon this question onwards of 2023.

const uri = "mongodb+srv://<user>:<password>@cluster0.xxxxxxx.mongodb.net/fruitDB?retryWrites=true&w=majority";
const mongoose = require("mongoose");
mongoose.connect(uri);

const fruitSchema = new mongoose.Schema ({
  key: value,
  key: value
});

const Fruit = mongoose.model("Fruit", fruitSchema);

Fruit.find({}).then((data) => {
  console.log(data);
}).finally(() => {
  mongoose.connection.close();
});

You need to resolve the promise returned by the .find() call --- if you try to console.log() the result before it's resolved then it will print the query object to the terminal. If you console.log() the result inside an anonymous function after appending .then() you ensure that the .find() promise has been resolved before proceeding and you print the resulting array of doc objects as intended.

I apologize if anything I've said is outright wrong, I do not have very much experience coding yet.

Upvotes: 0

Yerken
Yerken

Reputation: 1942

Use console.log(JSON.stringify(subjects, null, 4))

More about JSON.stringify

Upvotes: 1

Related Questions