简体   繁体   English

检索REST API中包含子文档的文档

[英]Retrieve Documents containing a subdocument in a REST API

I am trying to retrieve a list of documents that contain a sub doc to be listed on a web application. 我正在尝试检索包含要在Web应用程序中列出的子文档的文档列表。

I have my models setup as such: 我有这样的模型设置:

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

And the api controller setup as such: 以及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;
};

But am getting: 但是正在得到:

TypeError: undefined is not a function TypeError:未定义不是函数

What is the proper way to populate these subdocs and return the list of reviews to be consumed with a Web Application? 填充这些子文档并返回要与Web应用程序一起使用的评论列表的正确方法是什么?

Why do you have : var Game ? 为什么会有:var Game?

should be var Review . 应该是var Review

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM