As I delve into querying my MongoDB database using Mongoose, I encounter an issue. I am utilizing findOne to search by object_id, with the goal of retrieving the "start" and "end" fields from the corresponding object. However, instead of receiving the expected output, I consistently get 'undefined' logged to the console. Below are the details of my schema, an example object from my Events collection in MongoDB, and the code for my query:
Mongoose Schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var eventSchema = new Schema({
event: String,
city: String,
state: String,
date: String,
start: String,
end: Number,
radius: String,
team_1: String,
team_2: String,
object_id: String,
photos: []
})
module.exports = mongoose.model('Event', eventSchema);
Example object from MongoDB Event collection:
{
"_id": {
"$oid": "5495d1e2ac1e3caaeee84483"
},
"event": "Rockefeller Center",
"city": "New York",
"state": "New York",
"date": "",
"start": "December 18, 2014",
"end": "January 2, 2015",
"radius": "40",
"team_1": "",
"team_2": "",
"object_id": "10881503",
"photos": []
}
Server code:
//loop through incoming API POSTS. object_id is guaranteed to be in 'data'
req.body.forEach(function (data) {
var result = Event.findOne(
{object_id: data.object_id},
{ start: 1, end: 1 }
);
if (result) {
var startDate = result.start;
console.log(startDate);
} else {
console.log('object_id not found');
}
});