cities.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. 'use strict';
  2. import mongoose from 'mongoose';
  3. import cityData from '../../InitData/cities'
  4. const citySchema = new mongoose.Schema({
  5. data: {}
  6. });
  7. citySchema.statics.cityGuess = function(name){
  8. return new Promise(async (resolve, reject) => {
  9. const firtWord = name.substr(0,1).toUpperCase();
  10. try{
  11. const city = await this.findOne();
  12. Object.entries(city.data).forEach(item => {
  13. if(item[0] == firtWord){
  14. item[1].forEach(cityItem => {
  15. if (cityItem.pinyin == name) {
  16. resolve(cityItem)
  17. }
  18. })
  19. }
  20. })
  21. }catch(err){
  22. reject({
  23. name: 'ERROR_DATA',
  24. message: '查找数据失败',
  25. });
  26. console.error(err);
  27. }
  28. })
  29. }
  30. citySchema.statics.cityHot = function (){
  31. return new Promise(async (resolve, reject) => {
  32. try{
  33. const city = await this.findOne();
  34. resolve(city.data.hotCities)
  35. }catch(err){
  36. reject({
  37. name: 'ERROR_DATA',
  38. message: '查找数据失败',
  39. });
  40. console.error(err);
  41. }
  42. })
  43. }
  44. citySchema.statics.cityGroup = function (){
  45. return new Promise(async (resolve, reject) => {
  46. try{
  47. const city = await this.findOne();
  48. const cityObj = city.data;
  49. delete(cityObj._id)
  50. delete(cityObj.hotCities)
  51. resolve(cityObj)
  52. }catch(err){
  53. reject({
  54. name: 'ERROR_DATA',
  55. message: '查找数据失败',
  56. });
  57. console.error(err);
  58. }
  59. })
  60. }
  61. citySchema.statics.getCityById = function(id){
  62. return new Promise(async (resolve, reject) => {
  63. try{
  64. const city = await this.findOne();
  65. Object.entries(city.data).forEach(item => {
  66. if(item[0] !== '_id' && item[0] !== 'hotCities'){
  67. item[1].forEach(cityItem => {
  68. if (cityItem.id == id) {
  69. resolve(cityItem)
  70. }
  71. })
  72. }
  73. })
  74. }catch(err){
  75. reject({
  76. name: 'ERROR_DATA',
  77. message: '查找数据失败',
  78. });
  79. console.error(err);
  80. }
  81. })
  82. }
  83. const Cities = mongoose.model('Cities', citySchema);
  84. Cities.findOne((err, data) => {
  85. if (!data) {
  86. Cities.create({data: cityData});
  87. }
  88. });
  89. export default Cities