【问题标题】:Mongoose - Instantiate subSchema without parentMongoose - 实例化没有父级的子架构
【发布时间】:2020-07-27 12:57:22
【问题描述】:

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

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 - 我也尝试将两个模式放在同一个文件中,但如果不实例化整个“地方”模式,就无法到达嵌套数组(街道)。

谢谢。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema embedded-documents


    【解决方案1】:

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

    mongoose.model('street', StreetSchema);
    

    并在需要的地方导入它

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-02
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多