【问题标题】:How to nest the same schema in mongoose js如何在猫鼬js中嵌套相同的模式
【发布时间】:2015-12-18 14:49:17
【问题描述】:

我正在尝试使用 mongoose js 嵌套模式,特别是 same 模式,以创建树状结构。在此配置中,一个文档只能有 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 嵌套相同的模式?

【问题讨论】:

  • 请注意,在module.exports 定义中调用mongoose.model() 时,您在代码示例中创建了两次模型。

标签: javascript node.js mongodb


【解决方案1】:

警告已经告诉您“您只能使用 refs 或数组进行嵌套。”。这是一个猫鼬设计。

但你能做的是:

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);

【讨论】:

  • 谢谢,这里的关键是使用模式,而不是模型
猜你喜欢
  • 1970-01-01
  • 2019-03-22
  • 2015-09-21
  • 2019-07-20
  • 2017-06-12
  • 2019-10-02
  • 2014-06-22
  • 2019-01-16
  • 2017-01-28
相关资源
最近更新 更多