简体   繁体   English

如何在 Mongoose 中的 model 定义中使用另一个 model

[英]How to use another model in model definition in Mongoose

I'm writing mongoose in Node.js, ES6.我在 Node.js,ES6 中写 mongoose。

I first specified a model called Address , and would like to use the Address model in the definition of another model, Channel .我首先指定了一个名为Address的 model ,并想在定义另一个 model 时使用Address model, Channel

The codes are like the following:代码如下:

// Definition of Address // 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,
        }]
    });

For another model Channel , I would like to have a subscriber field, which is a list of Address .对于另一个 model Channel ,我想要一个subscriber字段,这是一个Address列表。

My tentative code is like the following:我的暂定代码如下:

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],
    });

However, I got error like this:但是,我收到这样的错误:

TypeError: Invalid schema configuration: `model` is not a valid type within the array `subscribers`

I wonder how should I implement the idea in NodeJS?我想知道我应该如何在 NodeJS 中实现这个想法?

If I got it right, you want each channel have an array of addresses specified to it.如果我做对了,你希望每个通道都有一个指定的地址数组。 so you have to specify address field in your channel this way:所以你必须以这种方式在你的频道中指定地址字段:

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'
                      }],
    });

you do not need Address model imported into your Channel model, MongoDB will recognize it automatically.您不需要将地址 model 导入您的频道 model,MongoDB 会自动识别它。 then when you want to create a channel document create it like this:然后当你想创建一个频道文档时,像这样创建它:

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.
})
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM