如何在控制台中打印mongoose find()数组文档

时间:2016-05-03 08:42:27

标签: node.js mongodb mongoose

我是mongoose的新手,并尝试使用mongodb node.js使用Mongoose ODM

我写了一些示例代码,如下所示:

示例代码 -

/*!
 * 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);
    });
  });
});

我想使用mongoose模型返回的console.log()在控制台中打印主题,但它只打印出这样的内容 -

[ [object Object], [object Object] ]

我也试过console.dir(),但结果与上面相同。

1 个答案:

答案 0 :(得分:0)

使用console.log(JSON.stringify(subjects, null, 4))

有关JSON.stringify

的更多信息