如何在mongoose中生成子模型

xbp102n0  于 2023-10-19  发布在  Go
关注(0)|答案(3)|浏览(108)

我试着模仿下面的。
我有一个名为Brickparent model,它有一些属性。将有5+类型的砖,都将有自己的具体属性,这是必要的。
我希望能够选择某个客户ID的所有砖后,无论类型(TwitterBrick,facebookBrick等)是.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('Brick', new Schema({ 
    type: String, 
    userid: { type: String, required: true},
    animationspeed: { type: Number, min: 1, max: 100 }, 
    socialsite: String,     // none, twitter, instagram
    socialsearchtags: String,
    tagline: { type: String, minlength:3,maxlength: 25 },

}));

子节点的例子是TwitterBrick。现在是:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('TwitterBrick', new Schema({ 
    bgColor1: String, 
    bgColor2: String,
    bannerBgColor1: String,
    bannerBgColor2: String,
}));

TwitterBrick应该继承Brick的属性,但我不知道如何继承。你能帮我在正确的方向吗?
谢谢你,谢谢

ocebsuys

ocebsuys1#

我的解决方案是在brickSchema中设置一个新的“content”字段,并拆分到不同的文件中:

brick.schema.js

var mongoose = require('mongoose');

    module.exports = { 
          type: String, 
          userid: { type: String, required: true},
          animationspeed: { type: Number, min: 1, max: 100 }, 
          socialsite: String,     // none, twitter, instagram
          socialsearchtags: String,
          tagline: { type: String, minlength:3,maxlength: 25 },
          content: {type:mongoose.Schema.Types.Mixed, required: false, default: null}
    }

brick.model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var BrickSchema = new Schema(require('brick.schema.js'));
module.exports = mongoose.model('defaultBrick', BrickSchema, 'Bricks');

twitterBrick.model.js

var mongoose = require('mongoose');
  var Schema = mongoose.Schema;  
  var brickSchema = require('brick.schema.js');

  brickSchema.content = new Schema({
  bgColor1: String, 
  bgColor2: String,
  bannerBgColor1: String,
  bannerBgColor2: String,
});

var BrickSchema = new Schema(require('brick.schema.js'));
module.exports = mongoose.model('twitterBrick', BrickSchema, 'Bricks');

希望能帮上忙!

vd2z7a6w

vd2z7a6w2#

只需添加Brick模型作为属性(组合)。它将补偿这一点。或者仅仅依靠为https://github.com/briankircho/mongoose-schema-extend安装mongoose插件,看看这个。

vxf3dgd4

vxf3dgd43#

这是因为你没有**“require”前一个文件**,所以从技术上讲,它超出了范围,TwitterWallBrickSchema不知道什么是“BrickSchema”。* 要么将两个模型放在同一个文件中,要么要求第一个文件放在第二个文件中 *。

相关问题