Instructions on selectively sorting an array within a MongoDB collection document

Seeking guidance as a newcomer to MongoDB. I am attempting to create a collection in my database with a single document that contains a key `cities`, which is an array comprising of 124247 objects. Below is the code snippet for reference:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require("mongoose");
const cities = require('cities.json');
const Schema = mongoose.Schema;
const db = mongoose.connection;
const app = express();

mongoose.connect("mongodb://localhost:27017/cities");

db.once("open", function() {
  console.log("Connection established successfully.");
})

const cityScheme = new Schema({
  cities: Array
});

const WorldCities = mongoose.model("WorldCities", cityScheme);
const myCities = new WorldCities({
  cities: cities
}).save().then(data => console.log({}.toString.call(data.cities), 'dataaa'));

WorldCities.find({
  name: "Yerevan"
}, function(err, data) {
  console.log(data, 'Armenia');
});
cityScheme.statics.getSearchedcity = function(res) {
  this.find({}, (err, citysList) => res.json({
    citysList
  }));
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/api/city', (req, res) => {

})

app.listen(3000);

You can access the cities.json file link here: Cities.json.

I am currently looking to retrieve the city named Yerevan but unsure of the approach to take. Any insights would be appreciated.

Answer №1

It appears that you are utilizing mongoose and based on the structure of your original data, it looks like you are specifically searching for a single document. Your schema likely includes a property called cities which holds the city objects from your JSON data. In order to achieve this, you can use the following code:

WorldCities.findOne({
  'cities.name': "Yerevan"
}, function(err, result) {
  // process the result here
  console.log(result);
});

By using the findOne method, you can locate and retrieve a single document, providing it in the callback function.

Give this code a try to see if it fetches the desired record for you.

Answer №2

Implement the .filter method

Example:

arrayOfCountries.filter(country => country.name === "Armenia")

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

Pattern-Based jQuery Selectors

I am looking for a way to use jQuery to select all paragraphs < p > within a < div > that contain time stamps with the following formatting patterns: <p>[22:48]</p> or <p>[22:48 - Subject Line]</p> Can someone provi ...

Guide on sending a JSON response from an API endpoint in Next.js

As I work on developing a small REST API for a Next.js application, I encountered an interesting issue. Initially, when I placed my route.ts file in the directory structure rootDir -> app -> api -> hello -> route.ts with the following code snip ...

Utilizing milliseconds to establish a date

At the moment, I have implemented a date picker on the front-end of my application. Once a user selects a date, the date in milliseconds is then sent to my Node.js backend. However, I am encountering an issue where I am receiving an "Invalid Date" error wh ...

VueSax notifications are showing up in the wrong place

Could it be my fault or is it due to the alpha status of vuesax that the notifications I want to use are displaying incorrectly? Here is the code extracted from the documentation: openNotification (title_, text_) { //This code is placed inside Vue methods ...

Notification of an uncaught promise being rejected

After creating this function, I keep encountering the Unhandled Promise Rejection Warning. Despite my attempts to refactor it, I just can't seem to get it right. router.post('/authenticate', function (req, res) { User.findOne({username: req ...

Can you explain the convention for boolean parameters in JavaScript or React?

Currently working with React and seeking to implement a basic setter using useState. For instance: const [isOpen, setIsOpen] = useState(false); const handleIsOpen = (value:boolean) => { setIsOpen(value) } I'm unsure about the most appropriate ...

Encountering a TypeError while exporting routes in ExpressJS 4.0

Would appreciate any suggestions on solving the error below, as I'm currently stuck: ~/public_html/server/routes/api.js:10 api.use(function(req, res, next){ ^ TypeError: Cannot call method 'use' of undefined at Object.<anonymous& ...

I'm having trouble getting Socket.io to function properly with my Node/Express application

Using openshift with express, I have been experiencing difficulties configuring socket.io. No matter what adjustments I make, it seems to disrupt my application. What could be the issue? Interestingly, when I disable the sections related to socket.io, the ...

What could be causing the function to not execute before the rest of the code in the React App?

My lack of expertise may be the reason, but I'm unsure how to address this issue: Here's what I have: A button labeled "Check numbers" <Button fullWidth variant="contained" onClick={this.checkOptOut ...

Create an express server that can stream mp3 files with the functionality to easily skip forward or rewind

My express server is set up to either download or stream an mp3 file, and here is the code: const express = require('express'); const fs = require('fs'); const app = express(); app.use('/mp3', express.static(__dirname + &apo ...

Exploring JSON data structures using autocomplete functionalities

Here's the code I'm working with: <s:hidden id="s" value="%{Users}"/> The variable Users contains an array list of User objects. This code is written in Javascript. I want to access Users as JSON for auto-complete functionality: var valu ...

Node.js is refusing to render the next page even after successfully rendering the initial page, which is causing a hindrance in my workflow

Hey there, I'm facing an issue in my node.js app main process. After the login process, if the user type is 'viewer', I want to render the 'depot_list_pg' view. When a user selects a depot from the list by clicking a button, I aim ...

The Heroku system encountered an issue: ENOENT - file or directory not found, trying to access '.env'

I'm encountering issues while attempting to deploy my application to Heroku: Error: ENOENT: no such file or directory, open '.env' 2019-04-10T01:38:23.050188+00:00 app[web.1]: 1 at Object.openSync (fs.js:438:3) 2019-04-10T01:38:23 ...

Ways to refine date results using JavaScript

Here is the JavaScript code I have: $(".datepicker").datepicker(); $(".datepicker-to").datepicker({ changeMonth: true, changeYear: true, maxDate: "0D" }); This code ensures that the date selected cannot be beyond the cur ...

Search for objects in an array that contain a specific word in a string field

Upon running a query on an extensive ontology using Jena, I exported the outcome in JSON format to a MongoDB collection named items within a database named galileo. Now, my goal is to search this collection for items based on their names (stored in the ...

Ten instances of $digest() being triggered upon the implementation of custom filters

I am struggling with the following angular markup: <tr ng-repeat="dia in dias"> <td>{{ dia[0].fecha }}</td> <td ng-repeat="bloque in bloques"> <div ng-repeat="hora in dia|soloBloque:bloque|sacarHoras"> ...

Tips for successfully retrieving a span value in VUE

I am working with forms <input type="text" v-model="email"> <span>Extracted Value</span> Can someone help me figure out how to pass the value from the span element? data () { return { email: '/*Here goes the extracted valu ...

Utilize a variable within a Jade include statement

I'm currently using Jade and Express and I want to include a variable in my include statement. Here is an example of what I am trying to achieve: app.js app.get('/admin', function (req, res) { var Admin = require('./routes/admin/app ...

FadeOut/FadeIn Iframe Animation

Help needed with making an iframe fade in and out using jQuery. Something seems off with the code and I can't figure out why it's not working. Can anyone spot the mistake? HTML <body> <center> <div class="headbackground" ...

Guide on converting arrays and sending this information in Node.js

I managed to retrieve quiz data and now I want to enhance it by mapping each answer to its respective quiz. I have a feeling that I should use something like forEach.push, but I haven't quite figured out the exact method... const API_KEY="https: ...