[英]How to use another model in model definition in Mongoose
我在 Node.js,ES6 中写 mongoose。
我首先指定了一个名为Address
的 model ,并想在定义另一个 model 时使用Address
model, 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,
}]
});
对于另一个 model 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`
我想知道我应该如何在 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'
}],
});
您不需要将地址 model 导入您的频道 model,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.
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.