如何从MongoDB返回数据

时间:2014-12-22 01:42:16

标签: javascript mongodb mongoose

我正在尝试使用Mongoose查询我的MongoDB数据库。我正在使用findOne按object_id进行搜索,目的是从相应的对象返回“start”和“end”字段。但是,我没有将两条消息中的一条记录到控制台,而是“未定义”。我的架构,我的Events集合中的示例对象和查询代码如下:

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

来自MongoDB事件集合的示例对象:

{
  "_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": []
}

服务器代码:

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

1 个答案:

答案 0 :(得分:2)

Mongoose为MongoDB提供了一个异步接口,因此findOne不返回找到的文档,它将它传递给您提供的另一个参数的回调函数。

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

});