Tips for sorting queries within a collection view in Mongoose:

I am working with Mongoose and creating a view on a collection.

  NewSchema.createCollection({
    viewOn: originalModel.collection.collectionName,
    pipeline: [
      {
        $project: keep.reduce((a, v) => ({ ...a, [v]: 1 }), {}),
      },
    ],
  });

This process involves generating a new schema that only displays specific fields defined as keep.

The resulting model includes the following pipeline:

{
  '$project': {
    uuid: 1,
    name: 1,
    description: 1,
    image_url: 1,
    price: 1,
    avg_rating: 1
  }
}

However, when executing queries on this new schema like:

const res = await NewSchema.find({name: {$regex: keywords, $options: 'i' }}).sort({ 'price': -1 })

The search results still include all data from the collection. Filtering works correctly when querying the base collection. Is there a way to apply filters to a query in Mongoose on a model that is a view of another schema?

Answer №1

Prior to creating any models and schemas, it is necessary for you to add the line

mongoose.set('strictQuery', false)
. This advice was provided by Valeri Karpov, the developer of mongoose, in a GitHub discussion.

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

I am looking for guidance on how to effectively utilize a JSON object that is stored in the constructor of my component, particularly when triggering

Below is the object I have in my constructor. I am passing a value from a previous component to the one below. I receive the item json object, but I need to use it when I click. constructor(public navCtrl: NavController, public navParams: NavParams) { ...

What is the best way to implement a custom NgbDateParserFormatter from angular-bootstrap in Angular 8?

Currently, I am working on customizing the appearance of dates in a form using Angular-Bootstrap's datepicker with NgbDateParserFormatter. The details can be found at here. My goal is to display the date in the format of year-month-day in the form fi ...

Enabling authentication for MongoDB on Ubuntu Desktop ensures a secure way to access your

Currently using Ubuntu 16.04 and attempting to enable authentication in mongodb I have created a new User with the following code: db.createUser({ user:"Sun", pwd:"Sun", roles:[{role:"userAdmin",db:"pet"}] }) I have verified the user with: db.getUsers( ...

Which JavaScript framework tackles the challenges of managing asynchronous flow, callbacks, and closures?

I have a strong aversion to JavaScript. I find it to be quite messy and disorganized as a language. However, I recognize that my lack of proficiency in coding with it may contribute to this perception. These past few days have been incredibly frustrating ...

Transitioning from one provider to another and encountering the error message "Cannot read property prompt of undefined."

This is an example of an alert service in TypeScript public Alert = { prompt: () => { return new Promise((resolve, reject) => { let prompt = this.alertCtrl.create({ title: 'Enter username', ...

Struggling with the implementation of a form that communicates between the client and server sides, utilizing MongoDB, Node.js, and HTML?

I am relatively new to this field. Currently, I am utilizing twitter bootstrap for HTML, CSS, and JS, node.js for server-side operations, and mongodb for no-sql databases. I have been exploring various aspects and now seeking guidance or suggestions on how ...

Why can't Angular iterate through objects using ngFor in Typescript?

Here's what I currently have: public posts: QueryRef<PostsInterface>; this.posts = this._postService.get(); //in ngOnInit In my HTML file, it looks like this: <mat-card *ngFor="let post of posts | async"> This allows me to display eac ...

Remove a file using Mongoose and Express by simply pressing a button

Trying to delete a connected account using Express and Mongoose. When the user clicks on a button (confirming their desire to delete their account), I want their account to be removed from my user's collection. HTML code snippet: <div class=" ...

running the same command on multiple collections in the mongo shell

I am currently working on a task involving date conversion across multiple collections: db.u201409.find().snapshot().forEach( function (e) { e.sta = new Date(e.start); e.sto = new Date(e.stop); db.u201409.save(e); } ) This code snippet is ...

The Angular Material side navigation module is not being acknowledged

Currently, I am utilizing Angular version 9.1.11 in conjunction with Angular Material version 9.2.4. The issue arises when attempting to import the MaterialSidenavModule, which is required for utilizing components like mat-sidenav-container. Below is a sn ...

Is it possible to pass a string of IDs to a MongoDB delete function for removal?

I have a list of specific Ids that I need to remove. To do this, I am retrieving my collection from the database and passing it as a resource. My aim is to loop through the collection and delete each of the specified Ids. Previously, I was deleting record ...

Insert information into a 3-tiered nested Angular FormArray within interconnected dropdown fields

After trying to retrieve data from an API call to populate a select form field, I encountered difficulties setting the value correctly using a FormArray. This led me to creating a FormArray with 3 nested levels in Angular, taking reference from this examp ...

Similar to mongoose's schema.pre function, Prisma allows you to perform actions

After transitioning my side project from MongoDB (mongoose) to PostgreSQL, I had to select an ORM to avoid writing raw SQL queries. Currently considering Sequelize, TypeORM, and Prisma, I am leaning towards Prisma and have started exploring some tutorials. ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

Encountering an Eslint issue: "Function missing return type" while adding a styled component to _document.tsx in Next.js

Setting up my NextJS project with styled components and Typescript has been my current focus. After consulting the official NextJS documentation, I successfully configured the _document.tsx file, which appears like this: import Document, { DocumentContext ...

Guide to uploading files from various fields within a single MongoDB collection using Multer

I need help with uploading images from multiple fields in the same collection. Currently, I can only upload using one field. route : service.js router.post('/register', upload.array('daycare.DCImage',10),(req, res) => { var paths ...

What is causing the reluctance of my Angular test to accept my custom form validation function?

I'm currently facing an issue with testing an angular component called "FooComponent" using Karma/Jasmine. Snippet of code from foo.component.spec.ts file: describe('FooComponent', () => { let component: FooComponent let fixture ...

Discovering a subdocument within a different model

I have a model and collection set up like this. User.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const UserSchema = new Schema({ name: String, email: String, //convert to contacts with type Object username: S ...

Having trouble retrieving records using findOne() when using a custom ID for inserting records in mongoDB

After inserting records into my mongoDB schema with the command: > db.records.insert( { _id: "6", "name": "Ashish", "City": "Dallas" } ) When I attempt to retrieve them using http://localhost:6001/api/employees/, the response I receive is as follows: ...