当添加新类别时,猫鼬模式会产生错误

nig*_*ode 1 mongoose mongodb node.js

我有两个模式,一个集合,另一个类别。一个集合有很多类别,一个类别可以有很多集合项。

我希望稍后再创建一个过滤器。

类别架构

const mongoose = require('mongoose')

let categorySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  collections: [{ type: mongoose.Types.ObjectId, ref: 'Collection' }]
})

module.exports = mongoose.model('category', categorySchema)
Run Code Online (Sandbox Code Playgroud)

收集模式

const mongoose = require('mongoose')

let collectionSchema = new mongoose.Schema({
  ...
  categories: [{
    type: mongoose.Schema.Types.ObjectId, ref: 'categories',
    required: true
  }]
})

module.exports = mongoose.model('collection', collectionSchema)
Run Code Online (Sandbox Code Playgroud)

截断此内容以保持相关性。

我现在不打算填充引用,因为我现在只是在做后端,所以我现在仅渲染JSON。

我可以创建多个类别

图片

并且我可以创建一个具有类别的集合,因为一个集合必须至少具有一个类别

图片

我可以编辑收藏夹并添加新类别

图片

但是,有时我似乎收到以下错误

图片

我不确定为什么应用程序中的数据库可能没有更新,我使用的是nodemon,所以我不太确定问题可能在这里。

O'D*_*ett 5

const CollectionSchema = new Schema({
  name: String
  categoryName: String
});

const CategorySchema = new Schema({
  name: String
});

CollectionSchema.virtual('category', {
  ref: 'Category', // The model to use
  localField: 'name', // Find people where `localField`
  foreignField: 'categoryName', // is equal to `foreignField`
  // If `justOne` is true, 'members' will be a single doc as opposed to
  // an array. `justOne` is false by default.
  justOne: false,
  options: { sort: { name: -1 }, limit: 5 } //you can add options as well
});

const Category = mongoose.model('Category', CategorySchema);
const Collection = mongoose.model('Collection', CollectionSchema);

Collection.find({}).populate('category').exec(function(error, categories) {
  /* `categories.members` is now an array of instances of `Category` */
});
Run Code Online (Sandbox Code Playgroud)

链接有其他信息