Retrieving specific fields from a MongoDB document through Mongoose for flexible querying

Is there a way to exclude certain attributes such as email, logoUri, and personal info from a seller object when dynamically populating?

Below is the messageSchema:

const messageSchema = mongoose.Schema({
  chatId: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: "Chat",
  },
   ....
  // sender can be type of User or Seller
  sender: {
    type: mongoose.Schema.Types.ObjectId,
    refPath: "senderType",
    required: true,
  },
  senderType: {
    type: String,
    required: true,
    enum: ["User", "Seller"],
  },
  readOn: { type: Date },
  read: Boolean, //}, {
  sentOn: {
    type: Date,
    default: Date.now,
  },
});

Here is where I populate my schema:

const messages = await Message.find({ chatId: chatId })
      .populate("sender")
      .sort({
        sentOn: -1,
      });

Since each model has different attributes, is it possible to select based on the type of model being populated dynamically? For example, for the user model:

.select('-email -logoUri') 

For the seller model:

.select('-address')

Answer №1

To effectively manage use cases, it's essential to establish specific selectors for each model involved in the scenario

messageSelectors = {
  user: "-email -logoUri",
  seller: "-address",
  ...
}

Subsequently, whenever there is a need to utilize selectors for messages, you can simply choose selectors based on the criteria being selected

function selectMessageAttributesFor(type, query){
  //ensure that the type exists within messageSelectors
  selected = await Messages.find(query).select(messageSelectors[type]).exec(callback);
}

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

Having trouble saving post data using ajax in django

I am encountering an issue with saving my partial '_dim' while viewing the main template 'sheet_form_create.html'. Every time I try to post the data for my '_dim' partial, I receive an error. Any assistance would be greatly ap ...

Does MongoDB exhibit an asymmetrical return of data, with the full details of the first item in an array displayed while certain properties are omitted for the rest?

Exploring MongoDB for the first time, I am working on understanding its syntax and capabilities. In order to accomplish the task mentioned in the heading, my plan is to develop a promise that can execute two parallel queries on the document. One query will ...

The auto-complete feature is malfunctioning after retrieving input suggestions from a PHP file

My goal is to achieve the following: 1. Create a list of suggestions with same labels but different descriptions. 2. Upon selecting an item from the list, the input field of another item should change to the corresponding description of the selected item. ...

Validation in AngularJS is limited to only accepting integers with the use of the

Can you help me with validating positive integer numbers using the ng-pattern attribute? Currently, I have this pattern: ^[0-9]{1,7}(\.[0-9]+)?$/, but it also allows decimal values. I want to restrict it to only accept whole numbers. ...

Retrieve the product of two disabled textboxes' values

I need to automatically calculate the total of two textboxes when either one is changed, but I want to prevent users from manually inputting values. Therefore, these 2 textboxes will be disabled and filled from a dropdown menu. Edit: When I change the val ...

Using the Express router to handle GET requests results in failure, however using the app

During my exploration of this particular guide, I encountered an issue where the router methods were not functioning as expected. Upon using npm start and trying to access localhost:3000/api/puppies, a 404 error would consistently appear. However, after mo ...

Is it considered best practice to redirect directly? Addressing the question using Express and Node.js technologies

I have a couple of queries regarding express. When making a call to the API function below from a user login page, two questions come to mind. Is there a specific reason why res.send(token) is present in the code snippet below? It has been commented ...

Combining file and JSON data in React and Express: A guide to uploading both simultaneously

I am looking to send both a file and JSON data from a form using my react handle submission method. const formData = new FormData(); formData.append('File', selectedFile); const data = { name: 'vasu', email: 'example@example ...

The response I am receiving is showing a 404 error even though the request was made correctly

Hello, I'm facing a strange issue while trying to set up a contact form using express and sendGrid. The functionality of sending messages is working fine, but I keep getting a 404 error on the request. It's puzzling how the messages are being del ...

Displaying a specific fieldset based on the radio button selection

I have created a form to handle user input using PHP, with the initial question prompting the user to choose from three radio buttons for the "type" parameter - the options being "book", "journal", and "website". Here is what the code looks like: <stro ...

Guide on validating an email through a 6-digit code using Flutter, Node.js, and MongoDB

My goal is to create a registration process where users enter their email and password on a screen. After clicking "register", they should receive an email with a random 6-digit code for verification on the next page. I have everything set up, but I' ...

Viewing items in the WebStorm console using Nodejs

I love how WebStorm allows me to simply hover my mouse over an object in the code and inspect it right away, just like this: https://i.sstatic.net/7ra9R.png But I wonder if there is a way to do this from the console too, similar to Google web tools? Unf ...

What is the solution to the error message "Cannot assign to read only property 'exports' of object '#<Object>' when attempting to add an additional function to module.exports?"

I've been struggling for the past 5 days with this issue. Despite numerous Google searches, I haven't found a solution that works for me. I have a file called utils.js which contains useful functions to assist me. However, when I include the func ...

To iterate through a multi-dimensional array

I am facing an issue with fetching data within an array in the code below var str = "Service1|USER_ID, Service1|PASSWORD" var str_array = str.split(','); console.log(str_array) for(var i = 0; i < str_array.length; i++) { str_array[i] = st ...

Tips for implementing handlebars in express using .html file extensions

I've been thinking about switching to .html extensions instead of .handlebars or .hbs extensions. This way, I can develop using plain HTML for easier editing by frontend developers in their IDEs without the need for additional configurations. It will ...

Which edition of MongoDB is recommended for installation on Windows 6?

Is there a specific version of MongoDB available for Windows 7 64-bit? I couldn't find it on https://www.mongodb.com/download-center#community. Which version should I install for Windows 7? ...

The xslt code is failing to invoke the JavaScript function

I am currently utilizing xslt for the transformation of xml to html. Below is an example of an .xml file. <ImportOrganizationUtility-logging> <log-session module-name="ImportOrganizationUtility" end="17:54:06" start="17 ...

Create an interactive Chart.js displaying real-time data fetched through ajax requests, designed to be fully responsive. Addressing

Chart.js (http://www.chartjs.org/docs/) is the tool I'm using for charting purposes. I am looking to retrieve data from an Ajax request while ensuring that the chart is responsive. Within my HTML markup, I've included a canvas element like this ...

The Sequelize orm model validation function in Node.js is throwing an error and is not

Below is the definition of my User model: options: { tableName: 'cushbu_users', hooks:{}, timestamps:false, /*--field names and validation rules --*/ email:{ type:Sequelize.STRING, val ...

Is a fresh connection established by the MongoDB Node driver for each query?

Review the following code: const mongodb = require('mongodb'); const express = require('express'); const app = express(); let db; const options = {}; mongodb.MongoClient.connect('mongodb://localhost:27017/test', options, fu ...