ObjectId 的 NodeJS/Mongoose 模式数组

haz*_*zer 0 arrays schema mongoose node.js objectid

我正在尝试在 Mongoose 的架构中实现一个 ObjectId 数组。我在互联网上搜索,我发现这应该有效:

import mongoose from 'mongoose';
import Schema from 'mongoose';

const UserSchema = mongoose.Schema({
  nickName: {
    type: String,
    unique: true,
    required: true,
  },
  follows: [{
    type: Schema.Types.ObjectId, //HERE
    ref: 'User',
    default: []
  }],
}, {
  strict: true,
});

const User = mongoose.model('User', UserSchema);
export default User;
Run Code Online (Sandbox Code Playgroud)

或这个

follows: {
          type: [Schema.Types.ObjectId], // HERE
          ref: 'User',
          default: []
  },
Run Code Online (Sandbox Code Playgroud)

我知道它们并不完全相同,但不是在这两种情况下都工作,我有这个错误:

 Invalid schema configuration: `ObjectID` is not a valid type within the array `follows`.
Run Code Online (Sandbox Code Playgroud)

我不知道他为什么告诉我 ObjectID(带有大写“ID”)无效,因为我没有声明任何这些。

我怎样才能做一个 objectId 数组?我想要一个 ObjectId 数组,通过引用模式“用户”和用户关注的人

[编辑] 正如 Bhanu Sengar 在评论中提到的,我不得不在 Schema 之前加上“猫鼬”。

[{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }] 
Run Code Online (Sandbox Code Playgroud)

正如 Halil SAFAK 所说,我删除了默认值。

它也不起作用,因为我在两个导入之间存在冲突

import mongoose from 'mongoose';
import Schema from 'mongoose';
Run Code Online (Sandbox Code Playgroud)

小智 5

我已经使用猫鼬填充属性检查我的代码。这将有助于您理解。

类别架构

const mongoose  = require('mongoose');
const timestamps    = require('mongoose-timestamp');

const cateorySchema = new mongoose.Schema({
  category_name: {
    type: String,
    trim: true,
    required: true,
  },
  active: {
        type: Boolean,
        default: true,
    }
});

cateorySchema.plugin(timestamps); // automatically adds createdAt and updatedAt timestamps
module.exports = mongoose.model('Category',cateorySchema);
Run Code Online (Sandbox Code Playgroud)

子类别架构

'use strict'

const mongoose    = require('mongoose');
const timestamps    = require('mongoose-timestamp');

const subCategorySchema = new mongoose.Schema({
    categories:{ type: mongoose.Schema.Types.ObjectId, ref: 'Category' },
    subcategorytitle:{
      type:String,
      trim:true,
      required: true
    },
    active: {
        type: Boolean,
        default: true
    }
});
subCategorySchema.plugin(timestamps); // automatically adds createdAt and updatedAt timestamps
module.exports = mongoose.model('Subcategory',subCategorySchema);
Run Code Online (Sandbox Code Playgroud)

我希望这能帮到您。如果您有任何疑问,请告诉我。