Javascript 如何在Mongoose的模型定义中使用其他模型

Javascript 如何在Mongoose的模型定义中使用其他模型,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我正在Node.js中编写mongoose,ES6 我首先指定了一个名为Address的模型,并希望在另一个模型Channel的定义中使用Address模型 代码如下所示: import mongoose from 'mongoose'; import {Address} from './Address.js'; export const Channel = mongoose.model('Channel', { id: mongoose.SchemaTypes.O

我正在Node.js中编写mongoose,ES6

我首先指定了一个名为
Address
的模型,并希望在另一个模型
Channel
的定义中使用
Address
模型

代码如下所示:

import mongoose from 'mongoose';
import {Address} from './Address.js';
export const Channel = mongoose.model('Channel',
    {   
        id: mongoose.SchemaTypes.ObjectId,
        name: String,
        path: String,
        subscribers: [Address],
    });
//
地址的定义

import mongoose from 'mongoose';
export const Address = mongoose.model('Address',
    {   
        id: mongoose.SchemaTypes.ObjectId,
        customer_id: String,
        addresses: [{
            address_type: String,
            address_info: String,
        }]
    });
对于另一个型号的
频道
,我想要一个
订户
字段,它是
地址
的列表

我的暂定代码如下:

import mongoose from 'mongoose';
import {Address} from './Address.js';
export const Channel = mongoose.model('Channel',
    {   
        id: mongoose.SchemaTypes.ObjectId,
        name: String,
        path: String,
        subscribers: [Address],
    });
但是,我得到了如下错误:

TypeError: Invalid schema configuration: `model` is not a valid type within the array `subscribers`
import {Address} from './Address';
import {Channel} from './Channel';

async function createChannel(){
  Channel.create({
                  name: 'theName',
                  path: 'thePath',
                  subscribers: [await Address.find()] //you can add all addresses by just use find or use your specific query to find your favored addresses.
})
}

我想知道我应该如何在NodeJS中实现这个想法?

如果我做对了,您希望每个通道都有一个指定给它的地址数组。因此,您必须以以下方式指定频道中的地址字段:

import mongoose from 'mongoose';
//import {Address} from './Address.js';
export const Channel = mongoose.model('Channel',
    {   
        id: mongoose.Schema.Types.ObjectId,
        name: String,
        path: String,
        subscribers: [{
                       type: mongoose.Schema.Types.ObjectId,
                       ref: 'Address'
                      }],
    });
您不需要将地址模型导入通道模型,MongoDB将自动识别它。然后,当您要创建频道文档时,请按如下方式创建:

TypeError: Invalid schema configuration: `model` is not a valid type within the array `subscribers`
import {Address} from './Address';
import {Channel} from './Channel';

async function createChannel(){
  Channel.create({
                  name: 'theName',
                  path: 'thePath',
                  subscribers: [await Address.find()] //you can add all addresses by just use find or use your specific query to find your favored addresses.
})
}

您想要一个特定于每个频道的地址或地址数组吗?@Ako一个地址数组。谢谢如果您使用导出默认值,那么您不需要在导入对象周围使用{}。非常感谢!它应该是
ref:'Address'
,因为在
Address
的模型定义中,我使用的是大写字母?谢谢,一定是
ref:“Address”
大写字母A,我的错,对不起。我编辑我的答案。如果这回答了你的问题,我会很高兴你接受它作为答案。