Mongoose - 在没有父级的情况下实例化 subSchema

Mongoose - Instantiate subSchema without parent

我正在尝试分别创建文档和子文档。 架构:

const mongoose = require('mongoose');
require('./streets');


const PlaceSchema = new mongoose.Schema({
  place1: String,
  streets: [{type: mongoose.Schema.Types.ObjectId, ref: 'streetSchema'}]
});

module.exports = mongoose.model('place', PlaceSchema);

子架构:

const mongoose = require('mongoose');

const StreetSchema = new mongoose.Schema(
  {
    trafficLights: Number,
    shops: Number,
    busStops: Number,
  },
  { strict: false }
);

module.exports = StreetSchema;

然后我尝试自己实例化街道:

const place = // ...get a certain place from DB;

const street = new Street({
  trafficLights: 1,
  shops: 2,
  busStops: 3,
});

place.streets.push(street)

我得到

Street is not a constructor

如何创建实例化 subSchema 并将其推入 'streets' 数组?

PS - 我也尝试将两个模式放在同一个文件中,但是如果不实例化整个“地点”模式就无法到达嵌套数组(街道)。

谢谢。

您应该创建一个模型,请在您的架构文件末尾添加此行

mongoose.model('street', StreetSchema);

并在您需要的任何地方导入它

const Street = mongoose.model('street');