[英]Can't get data from mongodb
I am trying to access a document and get the results to console. 我正在尝试访问文档并使结果进入控制台。 Mongoose debug shows that there is a document, yet returns an empty record. 猫鼬调试显示有一个文档,但返回空记录。
//mongoose connect to db
var db = mongoose.createConnection('mongodb://localhost/mean-dev1/', function(err) {
if (err) throw err;
});
db.once('open', function callback() {
var tripSchema = mongoose.Schema(
{ title: String,
fromDate: Date,
tillDate: Date,
price: Number,
details: String,
availability: Number
});
// Model definition
var TripObj = db.model('TripObj', tripSchema, 'tripmodel');
TripObj.find(function(err, data) {
if (!err){
console.log('%s', data); //gets undefined
console.log("written...", data);
}else{
throw err;
process.exit();
}
});
} }
and here is the console output 这是控制台输出
... ...
Migrations: Up to date at version 003 Mongoose: tripmodel.find({}) { fields: { title: 1 } } 迁移:最新版本003猫鼬:tripmodel.find({}){字段:{标题:1}}
is undefined? 是不确定的? written... [] 写... []
Figured it out, the problem was with my initial connection. 弄清楚了,问题出在我最初的连接上。 So changed the code a bit. 因此,更改了一下代码。
//connects to mongoose datasource and populates the data.json file in app
mongoose.disconnect();
mongoose.connect('mongodb://localhost/tripDB/', function(err) {
if (err) throw err;
}),
Schema = mongoose.Schema
var db = mongoose.connection;
db.once('open', function callback() {
var tripSchema = mongoose.Schema(
{
availability: Number,
details: String,
fromDate: Date,
price: Number,
tillDate: Date,
title: {type:String, ref:'TripObj'}
});
// Model definition
var TripObj = mongoose.model('TripObj', tripSchema, 'trips');
TripObj.find(function(err, data) {
if (!err){
var newdata = data;
//console.log('%s is undefined?', newdata);
fs.writeFileSync(path.join(__dirname, '../../../../' + 'content/themes/traveller/assets/js' + '/data.json'), JSON.stringify(newdata));
console.log("written succesfully", data);
process.exit();
}else{
throw err;
}
});
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.