I'm trying to nest schemas using mongoose js, specifically the same schema, to create a tree-like structure. In this configuration, a document can only have 1 parent, but the same document can be parent to more than one child. Here's how I approached it initially:
我正在尝试使用mongoose js嵌套模式,特别是相同的模式,以创建树状结构。在此配置中,文档只能有1个父文档,但同一文档可以是多个子文档的父文档。这是我最初接近它的方式:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
var mySchema = new Schema({
_id: {
type: ObjectId,
required: true
},
parent: {
_id: {
type: ObjectId,
ref: 'myModel'
},
required: true
}
});
var myModel = mongoose.model('myModel', mySchema);
module.exports = {
myModel: mongoose.model('myModel', myModel)
};
However, when I run this, I get the
但是,当我运行这个时,我得到了
A JavaScript error occurred in the main process Uncaught Exception: TypeError: Undefined type "undefined" at "file.required" Did you try nesting Schemas? You can only nest using refs or arrays.
主进程中发生JavaScript错误未捕获异常:TypeError:未定义类型“未定义”在“file.required”您是否尝试嵌套Schemas?您只能使用refs或数组进行嵌套。
I must be approaching this wrong. How do you nest the same schema using mongoose js?
我必须接近这个错误。如何使用mongoose js嵌套相同的模式?
1 个解决方案
#1
2
The warning already show you "You can only nest using refs or arrays.". This is a mongoose design.
警告已经显示“您只能使用refs或数组进行嵌套”。这是一种猫鼬设计。
But what you can do is:
但你能做的是:
var MySchema = new mongoose.Schema({
objectId: String,
parent: {
type: mongoose.Schema.ObjectId,
ref: 'MySchema'
},
})
This will use a schema inside a schema, then you can use a "pre save" to update the data of your parent. Or you can use a array of refs and keep with only 1 element.
这将使用架构内的架构,然后您可以使用“预先保存”来更新父级的数据。或者您可以使用refs数组并仅使用1个元素。
What a do is export the schemas and not the models, so you can nest it. like this:
做什么是导出模式而不是模型,所以你可以嵌套它。喜欢这个:
module.exports = MySchema;
Then I have some appModel to set the models of my collection of schemas, like this (app_model.js):
然后我有一些appModel来设置我的模式集合的模型,像这样(app_model.js):
if(mongoose.modelNames().indexOf('mySchema') < 0) mongoose.model('mySchema', mySchema);
#1
2
The warning already show you "You can only nest using refs or arrays.". This is a mongoose design.
警告已经显示“您只能使用refs或数组进行嵌套”。这是一种猫鼬设计。
But what you can do is:
但你能做的是:
var MySchema = new mongoose.Schema({
objectId: String,
parent: {
type: mongoose.Schema.ObjectId,
ref: 'MySchema'
},
})
This will use a schema inside a schema, then you can use a "pre save" to update the data of your parent. Or you can use a array of refs and keep with only 1 element.
这将使用架构内的架构,然后您可以使用“预先保存”来更新父级的数据。或者您可以使用refs数组并仅使用1个元素。
What a do is export the schemas and not the models, so you can nest it. like this:
做什么是导出模式而不是模型,所以你可以嵌套它。喜欢这个:
module.exports = MySchema;
Then I have some appModel to set the models of my collection of schemas, like this (app_model.js):
然后我有一些appModel来设置我的模式集合的模型,像这样(app_model.js):
if(mongoose.modelNames().indexOf('mySchema') < 0) mongoose.model('mySchema', mySchema);