简体   繁体   中英

How to use another model in model definition in Mongoose

I'm writing mongoose in Node.js, ES6.

I first specified a model called Address , and would like to use the Address model in the definition of another model, Channel .

The codes are like the following:

// Definition of 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 .

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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