In my Node.js code using the Mongoose package, I have the following questions:
1) When using the populate method, how can I remove the "total" field within the foundations array from the response? This array consists of references to another collection.
2) How can I filter only the campaigns with a state of "ACTIVE" using the "campaigns.state" field?
The Foundation model is defined as follows:
FOUNDATION model
var mongoose=require('mongoose');
var Schema = mongoose.Schema;
var foundation = new Schema({
twitter_account:{type: String, required: true, unique: true},
name:{type: String, required: true, unique: true},
pic_path: {type: String, required: true},
doc_path: {type: String, required: true},
campaigns: [{type: Schema.ObjectId, ref: 'Campaign'}]
},{
timestamps: true
});
module.exports = mongoose.model('Foundation', foundation);
The Campaigns model includes the Foundations field, which is an array of references to foundations. To avoid redundancy, I want to exclude it from the response.
var campaign = new Schema({
.............
foundations: [{type: Schema.ObjectId, ref: 'Foundation'}],
......................
}
This is the route of the API where I retrieve data:
var express = require('express');
var router = express.Router();
var Foundation=require('../models/Foundation');
var mongoose= require('mongoose');
var Promise = require("bluebird");
var _ = require('lodash');
//get all Foundations
router.get('/get/all', function(req, res, next) {
var results=Foundation.find({},{twitter_account:1,name:1,campaigns:1})
.populate('campaigns').exec(function (err, foundation) {
if (err) return handleError(err);
console.log(foundation);
res.send(foundation);
});
});
module.exports = router;
Here is the original response:
[
{
// Response data here...
},
{
// More response data...
}
The desired response should omit the foundation array field within campaigns objects:
[
{
// New response data here...
},
{
// More new response data...
}
Any ideas on achieving this? Thank you!
EDIT: For future reference, to filter objects with state='Active' in the Campaigns array using populate, I used the following code snippet:
.populate({path : 'campaigns' ,select :'-foundations', match:{state:'ACTIVE'}}).exec(function (err, foundation) {
if (err) return handleError(err);
console.log(foundation);
res.send(foundation);
});