我正在尝试使用 mongoose js 嵌套模式,特别是sameschema,创建树状结构。在此配置中,一个文档只能有 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)
};
但是,当我运行这个时,我得到了
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.
我一定是错误地对待这个问题。如何使用 mongoose js 嵌套相同的模式?
警告已经向您显示“您只能使用引用或数组进行嵌套。”。这是猫鼬设计。
但你能做的是:
var MySchema = new mongoose.Schema({
objectId: String,
parent: {
type: mongoose.Schema.ObjectId,
ref: 'MySchema'
},
})
这将使用架构内的架构,然后您可以使用“预保存”来更新父级的数据。或者您可以使用 refs 数组并仅保留 1 个元素。
要做的是导出模式而不是模型,这样您就可以嵌套它。
像这样:
module.exports = MySchema;
然后我有一些 appModel 来设置我的模式集合的模型,如下所示(app_model.js):
if(mongoose.modelNames().indexOf('mySchema') < 0) mongoose.model('mySchema', mySchema);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)