Norayr Ghukasyan
Norayr Ghukasyan

Reputation: 1408

How to filter MongoDB collection document's array

I am new in MongoDB and need a help. In my DB I am trying to create a collection, which has only one document.T hat document has a simple key ` cities, which is an array of 124247 objects. Here is my code

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 ok.");
})

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

This is the link to cities.json ` Cities.json .

So here I want to find the city with name Yerevan, but I don't know how to find it.

Upvotes: 0

Views: 228

Answers (2)

Akrion
Akrion

Reputation: 18525

You are using mongoose and from the look of your raw data it seems you are looking for only one document ... also it seems your schema is defined so that you have the cities property which contains the cities objects from your JSON so:

WorldCities.findOne({
  'cities.name': "Yerevan"
}, function(err, model) {
  // do something with the model here
  console.log(model);
});

findOne will locate only one document for you and return it in the callback.

See if this will get you the record.

Upvotes: 1

Gederson Chiquesi
Gederson Chiquesi

Reputation: 68

Use .filter

Ex:

arrayOfCiteis.filter(myC => myC.name === "Yerevan")

Upvotes: 0

Related Questions