我在Mongoose DB上创建了一个文档,其结构如下:
{
"_id": {
"$oid": "55bb2c92e4b0759bdca17fdc"
},
"email": "Customer1@xyz.com",
"serviceType": "Electricity",
"month": "JAN",
"year": "2015",
"bill": [
{
"PeakMsmt": "1",
"OffPeakMsmt": "2",
"Week": "Week1",
"WeekEndTimeStamp": "2015-10-10T00:00:00.000Z"
},
{
"PeakMsmt": "2",
"OffPeakMsmt": "3",
"Week": "Week2",
"WeekEndTimeStamp": "2015-11-10T00:00:00.000Z"
},
{
"PeakMsmt": "3",
"OffPeakMsmt": "4",
"Week": "Week3",
"WeekEndTimeStamp": "2015-12-10T00:00:00.000Z"
}
]
}
我的Node.JS代码是:
var mongoose = require("mongoose");
mongoose.connect('mongodb://MY_MONGO_DB_URL');
var oub = require('./OptimizeUtilityBill');
oub.find({email:'Customer1@xyz.com',serviceType:'Electricity',month:'FEB',year:'2015'},function(err,oubDBResult){
if(err){
console.log("Error: "+err);
}else{
console.log("OUB result: "+oubDBResult);
}
});
我在节点JS中的mongoose模式是:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var OptimizeUtilityBillSchema = new Schema({
email:String,
serviceType:String,
month:String,
year:String,
bill:[{PeakMsmt:String,
OffPeakMsmt:String,
Week:String,
WeekEndTimeStamp:String}]
});
module.exports = mongoose.model('optimizeUtilityBill', OptimizeUtilityBillSchema);
请帮助,我是node.JS和mongoose的新手。 我花了好几个小时试图让它工作,并且还搜索了很多Mongoose模式。但是无法查询mongoose。
运行此程序时,我得到以下结果:
答案 0 :(得分:0)
试试这个:
var mongoose = require("mongoose");
var db = mongoose.connect('mongodb://MY_MONGO_DB_URL');
var oub = require('./OptimizeUtilityBill');
db.on('error', function(){console.log('connection error')});
db.once('open', function (callback) {
oub.find({email:'Customer1@xyz.com',serviceType:'Electricity',month:'FEB',year:'2015'},function(err,oubDBResult){
if(err){
console.log("Error: "+err);
}else{
console.log("OUB result: "+oubDBResult);
}
});
});
您并没有等待连接真正开放。
答案 1 :(得分:0)
我的问题的解决方案在这里:
Mongoose find() not returning result
为了使其工作,我需要将我的架构导出为:
module.exports = mongoose.model('optimizeUtilityBills', OptimizeUtilityBillSchema,'optimizeUtilityBills');
注意:optimizeUtilityBills是mongoDB中我的文档的名称。
谢谢你的帮助。