问题
I have a website that lets people search for bands that are within 100 miles of the location they enter. It uses mongoDB's geospatial indexing to find the bands. Code works and is below.
When it finds the band, it sends the whole band back to the front end. The band object has a key of posts, where it stores all the posts from the band. I need it to send back the whole band object, as I use all the info for displaying the band.. BUT I also need the posts.. If the user searches an area with 50 bands and each band has 100 posts... it gets a bit cumbersome for the page to load all the posts.
Is there a way to limit how many posts get returned but still allow the whole band object to get sent back? Or should I just send the whole band object to the front end, and limit how many posts get loaded?
I have looked up the regular way of pagination - It seems like that would work for limiting the number of bands that come back rather than limiting the number of posts that come back.
Here is my route -
//Get Home bands near a point
router.get('/homeBands/:lng/:lat', (req, res) => {
quoteGenerator.find(
{
"bandLocation.geometry":
{ $near :
{
$geometry: {
type: "Point",
coordinates: [parseFloat(req.params.lng), parseFloat(req.params.lat)]
},
$maxDistance: 160934,
}
}
},
)
.then(
function(bands) {
res.send(bands)
})
});
Here is my schema - Posts is the array that I am worried about.
//Create Schema - Band
const AutoQuoteGeneratorSchema = new Schema({
baseCost: {
type: Number
},
mainDate: {
type: Object
},
quoteGenerator: {
type: Array,
required: true,
},
userId: {
type: String,
required: true,
},
type: {
type: String,
required: true,
},
bandName: {
type: String,
required: true,
},
bandBio: {
type: String,
required: true,
},
bandLocation: GeoSchema,
bandTour: [GeoSchema],
bandGenre: {
type: String,
required: true,
},
youtube: {
type: Array,
required: true,
},
published: {
type: Boolean,
required: true,
},
posts: {
type: Array,
required: true,
},
favorites: {
type: Array,
required: false
},
cancellationPolicy: {
type: String,
required: false
},
fbData: {
type: Object,
required: false
},
showTypes: {
type: Array,
required: false
},
googleData: {
type: Object,
required: false
}
});
回答1:
https://itnext.io/back-end-pagination-with-nodejs-expressjs-mongodb-mongoose-ejs-3566994356e0
You can use the pagination to get limited posts. Here is the sample project using pagination in Node.js
来源:https://stackoverflow.com/questions/61990531/express-and-mongo-db-advanced-pagnation