如何动态创建猫鼬模式?

问题描述 投票:0回答:2

我有一个可以在带有 MongoDB 和 mongoose 的 Node.js 上运行的应用程序。我的应用程序只是发送/删除/编辑表单数据,为此,我有这样的猫鼬模型:

var mongoose = require('mongoose');

module.exports = mongoose.model('appForm', {
    User_id : {type: String},
    LogTime : {type: String},
    feeds : [   
    {
        Name: {type: String},
        Text : {type: String},
    }
    ]
});

效果很好!

现在,我想向表单添加一个功能,以便用户可以向表单添加一个(或多个)字段,并在其中输入文本并发布。 在客户端创建动态功能没有问题,但我知道我的 mongoose.model 必须正确构建。 我的问题是:如何将该变量值(动态创建的表单数据名称及其文本)添加到猫鼬模式?

我发现建议使用

strict: false
Schema.Types.Mixed
。但是,我无法弄清楚... 我尝试过的:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var feedSchema = new Schema({strict:false});

module.exports = mongoose.model('appForm', feedSchema);

有什么建议吗?预先感谢!

node.js mongodb mongoose
2个回答
58
投票

通过将

strict: false
选项作为第二个参数提供给
Schema
构造函数,将其应用到现有模式定义:

var appFormSchema = new Schema({
    User_id : {type: String},
    LogTime : {type: String},
    feeds : [new Schema({
        Name: {type: String},
        Text : {type: String}
    }, {strict: false})
    ]
}, {strict: false});

module.exports = mongoose.model('appForm', appFormSchema);

如果您想将

feeds
保留为完全无模式,那么您可以使用
Mixed
:

var appFormSchema = new Schema({
    User_id : {type: String},
    LogTime : {type: String},
    feeds : [Schema.Types.Mixed]
}, {strict: false});

module.exports = mongoose.model('appForm', appFormSchema);

0
投票

在最新版本的 Mongoose 中,你可以使用这样的东西

const mongoose = require("mongoose");
const { Schema } = mongoose;

const assetSchema = new Schema(
  { name: { type: String, required: true } },
  { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } }
);

const Asset = mongoose.model("Asset", assetSchema);

const addDynamicField = (fieldName, type) => {
  assetSchema.add({ [fieldName]: { type, default: null } });
};

module.exports = { Asset, addDynamicField };

我们可以设置propertyName和它的类型

Eg:-
propertyName = "age"
propertyType = "Number"

addDynamicField(propertyName, propertyType);

这将在架构中创建动态属性,并且无需使用

{strict: false}

© www.soinside.com 2019 - 2024. All rights reserved.