【问题标题】:How to return data from MongoDB如何从 MongoDB 返回数据
【发布时间】:2015-02-20 03:12:58
【问题描述】:

我正在尝试使用 Mongoose 查询我的 MongoDB 数据库。我正在使用 findOne 通过 object_id 进行搜索,并旨在从相应的对象返回“开始”和“结束”字段。但是,我没有将两条消息之一记录到控制台,而是得到“未定义”。我的架构、我的事件集合中的示例对象和查询代码如下:

Mongoose 架构:

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

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-06-05
      • 2023-04-06
      • 2017-11-26
      • 1970-01-01
      • 2012-12-30
      • 2016-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多