How can I efficiently delete a property from a nested array of references in MongoDB using Mongoose.js, leveraging the populate method, and also utilizing one of the subarray fields as a filter?

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

Answer №1

If you want to retrieve specific data from related documents, you can use the populate method along with select in Mongoose.

var results = Foundation.find({}, {twitter_account:1, name:1, campaigns:1})
  .populate({path : 'campaigns', select:'-foundations'})
  .exec(function(err, foundation) {
    if (err) return handleError(err);
    console.log(foundation);
    res.send(foundation);
});

For more information on how to use populate in Mongoose, check out their documentation at http://mongoosejs.com/docs/populate.html.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Javascript alert: forgetting to add ; before statement causes SyntaxError

Seeking to incorporate a post-it application into my django website using Javascript/JQuery. Came across a tutorial and attempted to add it to my script, but encountered a SyntaxError: SyntaxError: missing ; before statement post-it.js:2:19 Not be ...

How can we tailor a function in NextJS to display specific content according to the link provided?

In my /pages/index.js file, I have the following code snippet: export default function Home() { return ( <div className={styles.grid_container}> <NavBar/> <div className={styles.center_pane}> <Overview/> ...

Node.js error: HTML audio file returns 404 on server but plays fine when accessed directly as an HTML file

I'm facing an issue with an HTML page that contains an autoplay tag for a song (the file is in mp3 format). When I open the page as a local file on my Mac, the song plays fine. However, when I try to run it using a node.js file with socket.io, the son ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

Ways to Retrieve the Index of Elements in the DOM Array Generated by the querySelectorAll() Function in JavaScript

const items = document.querySelectoAll('.class') console.log(items) // Array with 15 elements (This array contains a total of 15 elements) ...

Passing parent props to child components in Vue.js - A comprehensive guide!

Trying to understand the process of passing a prop from parent to child components. If I include the prop attribute with the #id within the child component tag, like Image cid="488484-49544894-584854", it functions correctly. However, I am interested in u ...

Inspect the data attribute and modify the class

I am looking to determine if a data attribute has a specific value and then update the class associated with it. For example, in my HTML code: <li class="country active" data-country-code="ca"><div class="flag ca"& ...

What is the best way to send an HTML form variable to a Perl script using AJAX?

My goal is to pass the HTML variable from the list menu to the Perl script using POST. However, when I try to do this, the jQuery ajax() function executes the Perl script without including the value obtained from document.getElementById. Below is the sni ...

Choose a new image by confirming your selection with a dialog box

I have a collection of images displayed in a grid, and I want to be able to select one of them to update the value with the chosen image. Before proceeding with the update, I need a confirmation prompt to ensure the user wants to proceed or cancel the acti ...

The problem with the connection between nodes is that the object function createServer does not have a static

I'm attempting to start my node server following an example from a book on AngularJS (server.js). var connect = require('connect'); connect.createServer( connect.static("../angularjs") ).listen(5000); At first, I encountered the error "obj ...

Automatic closure of Info Window on Google Maps is not functioning as expected

I have recently developed a map which you can view here. The issue I am facing is that when I click on the layers to see the InfoWindow, they do not automatically close when I click on another layer. The JavaScript code I am using is causing this problem. ...

What is the best way to retrieve scope variables from multiple directives?

I am working on a directive that represents a person with changing location attributes. My goal is to access all the locations together and plot them on a map using the angular-leaflet-directive. I'm struggling to figure out how to access these variab ...

Having trouble integrating VueX store and router into Mocha tests

Latest Update To view the issue on VueX git repository that has been created, please follow this link: https://github.com/vuejs/vuex/issues/1509 If you want to replicate the problem, here is the link to the repository: https://github.com/djam90/vuex-vue- ...

Ways to adjust the width of the Dialog box in Jquery UI to 60% of the window size

Currently, I am utilizing Jquery UI for a pop-up feature that displays a table populated through an Ajax call. The script implementation is as follows: <script> $(function() { $( "#dialog" ).dialog({ autoOpen: false, show: { ...

The use of Physijs and implementing setLinearVelocity for object movement

2-09-2015 - UPDATE: The code provided below is now functional with the use of setLinearVelocity(). If you were facing similar issues, this updated code may help you. Find the original question with the corrected code below... A player object has been deve ...

Configuring bitfinex-api-node with Node.js to efficiently handle data from the websocket connection

Apologies for the vague title of this question, as I am not well-versed in programming and even less so in node.js My goal is simple: I aim to utilize the bitfinex-api-node package (a node.js wrapper for the bitfinex cryptocurrency exchange) that I instal ...

Retrieve the information transmitted to an EJS file within a separately included JavaScript file

I'm currently utilizing express js to render a file by using: res.render('plain',{state:'admin'}) The file plain.ejs includes main.js: <script src ="/main.js"></script> I need assistance on how to access the state v ...

Enhance frontend user experience by automatically updating AJAX scripts using jQuery

I have a script that currently only works on the initial page load, but I want to modify it to automatically update every 30 seconds. How can I achieve this desired effect? $.ajax({ type: "GET", url: "Administration/data/people.xml" }) ...

This method or property is not supported by the object - How to call an Applet in Internet Explorer 9

cmd > java -version Java Version : "1.7.0_11" (Updated) Java(TM) SE Runtime Environment (build 1.7.0_11-b21) Java HotSpot(TM) Client VM (build 23.6-b04, mixed mode, sharing) browsers = IE7,IE8,IE9 (The functionality works smoothly in Google Chrome and ...

When working with multiple charts on Angular ChartJs, the data may not display properly

My goal is to display multiple Charts in a single page using Angular. I came across an Example that uses ViewChildren: const baseConfig: Chart.ChartConfiguration = { type: 'pie', options: { responsive: true, } }; @ViewChildren('c ...