0

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.

2
  • can you please share cities array content?? is there any name field in it which you want to search? Commented Aug 17, 2018 at 13:48
  • Of course, i edited and added it . Commented Aug 17, 2018 at 13:55

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use .filter

Ex:

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

2 Comments

I know the filter method pretty well , i just dont know how to access to that array
this is works for me, cities.filter(x => x.name === 'Sant Julià de Lòria').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.