我是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()
,但结果与上面相同。