【问题标题】:Retrieve Documents containing a subdocument in a REST API在 REST API 中检索包含子文档的文档
【发布时间】:2016-01-18 18:20:45
【问题描述】:

我正在尝试检索包含要在 Web 应用程序上列出的子文档的文档列表。

我的模型设置如下:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var storeSchema = new mongoose.Schema({
  name: String,
  address: String,
  phone: String,
  webUrl: String,
  coords: {type: [Number], index: '2dsphere'}
});

var reviewSchema = new mongoose.Schema({
  user: {type: String, required: true},
  store: { type: Schema.ObjectId, ref: 'Store' },
  review: {type: String},
  tags: [String]
});

mongoose.model('Review', reviewSchema);
mongoose.model('Store', storeSchema);

API 控制器设置如下:

var mongoose = require('mongoose');
var Game = mongoose.model('Review');

var sendJsonResponse = function(res, status, content) {
res.status(status);
res.json(content);
};

module.exports.gamesListByDistance = function(req, res) {
var lng = parseFloat(req.query.lng);
var lat = parseFloat(req.query.lat);
var maxDistance = parseFloat(req.query.maxDistance);

var point = {
    type: "Point",
    coordinates: [lng, lat]
};

var geoOptions = {
    spherical: true,
    maxDistance: theEarth.getRadsFromDistance(maxDistance),
    num: 10
};

Review.geoNear(point, geoOptions, function(err, results, stats) {
    console.log('Geo Results', results);
    console.log('Geo stats', stats)
    if (err) {
        console.log('geoNear error:', err);
        sendJsonResponse(res, 404, err);
    } else {
        results.populate(results, {path:'store', select:'name coords'},    function(err,reviews) {
            if (err) {
                sendJsonResponse(res, 400, err);
            } else {
                games = buildReviewsList(req, res, results, stats);
                sendJsonResponse(res, 200, reviews);
            }
        });

    }
});
};

var buildReviewsList = function(req, res, results, stats) {
  var reviews = [];
  results.forEach(function(doc) {
    reviews.push({
        distance: theEarth.getDistanceFromRads(doc.dis),
        store: doc.obj.store.name,
        status: doc.obj.status,
        tags: doc.obj.tags,
        _id: doc.obj._id
    });
});
  return reviews;
};

但我得到了:

TypeError: undefined is not a function

填充这些子文档并返回要与 Web 应用程序一起使用的评论列表的正确方法是什么?

【问题讨论】:

    标签: node.js mongodb rest mongoose


    【解决方案1】:

    为什么你有: 变种游戏?

    应该是var Review

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 2012-11-26
      相关资源
      最近更新 更多