简体   繁体   中英

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.

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:

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

What is the proper way to populate these subdocs and return the list of reviews to be consumed with a Web Application?

Why do you have : var Game ?

should be var Review .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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