Мангуста Субдокумент для Geojson - PullRequest
0 голосов
/ 03 июля 2019

Я не могу определить правильную схему точек многократного использования.Я только что скопировал пример схемы в https://mongoosejs.com/docs/geojson.html

Это ошибка, с которой я сталкиваюсь при запуске приложения node.js

/ home / ****** / projects / realista-api / node_modules / mongoose / lib / schema.js: 418 throw new TypeError ('Неверное значение для пути к схеме ' + prefix + key + '');^ TypeError: Неверное значение для пути к схеме coordinates

Я уже пытался использовать схему, не подлежащую повторному использованию.Путем непосредственного определения его в родительской схеме, и он работает

coordinates: {
    type: {
      type: String,
      enum: ['Point'],
      required: true
    },
    coordinates: {
      type: [Number],
      required: true
    }
  },

Вот код

import { Schema, Document } from 'mongoose';

interface Point extends Document {
  type: string,
  coordinates: Array<number>,
}

const PointSchema: Schema = new Schema({
  type: {
    type: String,
    enum: ['Point'],
    required: true
  },
  coordinates: {
    type: [Number],
    required: true
  }
}, {
  id: false
});

export {
  Point,
  PointSchema,
}

Я использую его как поддокумент в другой схеме

const ProjectSchema: Schema = new Schema({
  owner: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: false,
  },
  logo: {
    type: String,
    required: false,
  },
  name: {
    type: String,
    required: true,
  },
  location: {
    type: String,
    required: false,
  },
  suburb: {
    type: String,
    required: false,
  },
  stateCode: {
    type: String,
    required: false,
  },
  country: {
    type: String,
    required: false,
  },
  countryName: {
    type: String,
    required: false,
    unique: true,
    sparse: true,
  },
  coordinates: PointSchema,// this is the field in question
  commission: {
    type: Schema.Types.Decimal128,
    required: false,
  },
  tax: {
    type: Schema.Types.Decimal128,
    required: false,
  },
  propertyType: {
    type: Schema.Types.ObjectId,
    ref: 'PropertyType',
    required: true,
  },
  address: {
    type: String,
    required: false,
  },
  title: {
    type: String,
    required: false,
  },
  description: {
    type: String,
    required: false,
  },
  videoTour: {
    type: String,
    required: false,
  },
  matterPortUrl: {
    type: String,
    required: false,
  },
  currency: {
    type: String,
    required: false,
  },
  minPrice: {
    type: Schema.Types.Decimal128,
    required: false,
  },
  maxPrice: {
    type: Schema.Types.Decimal128,
    required: false,
  },
  otherPrice: {
    type: String,
    required: false,
  },
  featureLandSizeMin: {
    type: String,
    required: false,
  },
  featureLandSizeMax: {
    type: String,
    required: false,
  },
  featureLandSizeUnit: {
    type: String,
    required: false,
  },
  featureBuiltStart: {
    type: Date,
    required: false,
  },
  featureBuiltEnd: {
    type: Date,
    required: false,
  },
  featureNumOfLevel: {
    type: Number,
    required: false,
  },
  featureNumOfUnit: {
    type: Number,
    required: false,
  },
  featureFlooring: {
    type: String,
    required: false,
  },
  featureExterior: {
    type: String,
    required: false,
  },
  featureConcierge: {
    type: String,
    required: false,
  },
  indoorFeatures: {
    type: String,
    required: false,
  },
  outdoorFeatures: {
    type: String,
    required: false,
  },
  minBedrooms: {
    type: Number,
    required: false,
  },
  maxBedrooms: {
    type: Number,
    required: false,
  },
  minBathrooms: {
    type: Schema.Types.Decimal128,
    required: false,
  },
  maxBathrooms: {
    type: Schema.Types.Decimal128,
    required: false,
  },
  minParking: {
    type: Number,
    required: false,
  },
  maxParking: {
    type: Number,
    required: false,
  },
  csvVariationPending: {
    type: Boolean,
    required: false,
    default: false,
  },
  isPrivate: {
    type: Boolean,
    required: false,
    default: false,
  },
  status: {
    type: Boolean,
    required: false,
    default: false,
  },
  variations: [{
    type: Schema.Types.ObjectId,
    ref: 'ProjectVariation',
  }],
  deletedAt: {
    type: Date,
    required: false,
  }
}, {
  collection: 'projects',
  timestamps: true,
  strict: false,
});

Что я делаю не так?Заранее спасибо.

1 Ответ

0 голосов
/ 04 июля 2019

удалось заставить его работать. Надеюсь, что это поможет другим, кто разрабатывает с использованием node.js

Проблема была вызвана двумя причинами:

  1. Mongoose, когда объявляет вложенные документы (вложенные объекты или массив объектов), запутывается, когда в документе есть поле type, поскольку в концепции Mongoose это зарезервированное слово для объявления типа поля. В моем случае ключ type происходит от GeoJSON , поскольку MongoDB требует, чтобы он находился в этом формате. Вот ссылка с mongoose docs для лучшего понимания.

Я только что изменил PointSchema на этот

import { Schema, Document } from 'mongoose';

interface Point extends Document {
  type: string,
  coordinates: Array<number>,
}

const PointSchema: Schema = new Schema({
  type: {
    $type: String,
    enum: ['Point'],
    required: true
  },
  coordinates: {
    $type: [Number],
    required: true
  }
}, {
  _id: false,
  typeKey: '$type',
});

export {
  Point,
  PointSchema,
}
  1. У меня также проблема с циклической зависимостью в node.js при импорте / требовании PointSchema. Эта ошибка
/home/******/projects/realista-api/node_modules/mongoose/lib/schema.js:418 throw new TypeError('Invalid value for schema path ' + prefix + key + ''); ^ TypeError: Invalid value for schema path coordinates

произошло, потому что PointSchema не определена, когда я использую его в ProjectSchema.

W / c объясняет, почему проблемы в Mongoose Github предполагают, что в большинстве случаев, когда они сталкиваются с этой ошибкой, это происходит из-за неправильно написанных типов (ObjectID вместо ObjectId) или в моем случае неопределенный w / c является недопустимым типом.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...