gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:13:11 25 4
gpt4 key购买 nike

我是 mongoose 新手,并尝试使用 Mongoose ODMmongodbnode.js 结合使用。

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

示例代码 -

/*!
* 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() 但结果与上面相同。

最佳答案

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

更多关于JSON.stringify

关于node.js - 如何在控制台中打印 mongoose find() 数组文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36999478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com