ObjectId的NodeJS / Mongoose模式数组

时间:2019-02-25 07:21:25

标签: arrays node.js mongoose schema 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;

或此

follows: {
          type: [Schema.Types.ObjectId], // HERE
          ref: 'User',
          default: []
  },

我知道它们并不完全相同,但是在这两种情况下我都无法正常工作,

 Invalid schema configuration: `ObjectID` is not a valid type within the array `follows`.

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

我怎么做一个objectId数组? 我希望通过引用架构“ User”以及用户关注的人来组成ObjectId的数组

[ EDIT ] 正如Bhanu Sengar在评论中提到的那样,我必须在模式之前加上“猫鼬”。

[{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }] 

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

它也没有用,因为我两次进口之间有冲突

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

2 个答案:

答案 0 :(得分:0)

实际上,该错误不是在ObjectId中,而是在您的配置中。您在'follows'中定义objectId,然后将数组写为默认值,但这实际上不是ObjectId类型的对象类型,所以这是错误。您将不会有如下定义的问题。

follows: [{
    type: Schema.Types.ObjectId, //HERE
    ref: 'User'
  }],

follows: [Schema.Types.ObjectId],

在这两个定义中,MongoDB填充查询将起作用。

答案 1 :(得分:0)

我用过猫鼬的Populate属性检查我的代码。 这将帮助您理解。

类别架构

'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);

SubCategory架构

{{1}}

我希望这会对您有所帮助。如果您有任何疑问,请告诉我。