如何在猫鼬的模型定义中使用另一个模型

时间:2021-02-12 20:12:30

标签: javascript node.js mongodb mongoose

我正在用 Node.js、ES6 编写 mongoose。

我首先指定了一个名为 Address 的模型,并且想在另一个模型 Channel 的定义中使用 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, }] }); 的定义

Channel

对于另一个模型 subscriber,我想要一个 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], }); 的列表。

我的暂定代码如下:

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

但是,我得到了这样的错误:

{{1}}

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

1 个答案:

答案 0 :(得分:1)

如果我猜对了,您希望每个通道都有一个指定的地址数组。所以你必须以这种方式在你的频道中指定地址字段:

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

您不需要将 Address 模型导入到 Channel 模型中,MongoDB 会自动识别它。然后当你想创建一个频道文档时,像这样创建它:

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