MattDionis
MattDionis

Reputation: 3616

How to return data from MongoDB

I'm attempting to query my MongoDB database using Mongoose. I'm using findOne to search by object_id and aiming to return the "start" and "end" fields from the corresponding object. However, instead of getting one of the two messages logged to the console I get 'undefined'. My schema, example object from my Events collection, and query code are below:

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');
  }
});

Upvotes: 3

Views: 146

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

Mongoose provides an asynchronous interface to MongoDB, so findOne doesn't return the found doc, it passes it to a callback function that you provide as another parameter.

req.body.forEach(function (data) {

  Event.findOne(
    {object_id: data.object_id}, 
    { start: 1, end: 1 },
    function(err, result) {
      if (result) {
        var startDate = result.start;
        console.log(startDate);
      } else {
        console.log('object_id not found');
      }
    }
  );

});

Upvotes: 2

Related Questions