How to create mongoose schema dynamically?
Asked Answered
C

2

29

I have an app that works on node.js with MongoDB and mongoose. My app simply sends/deletes/edits form data and for that, I have such mongoose model:

var mongoose = require('mongoose');

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

and that works just fine!

Now, I would like to add a function to the form so that the user can add a field(or fields) to form and enter a text in it and post it. Creating that dynamic functionality on the client side is no problem but I understand that my mongoose.model has to be correctly structured. My question is: how do I add that variable values(dynamically created form data name and its text) to mongoose schema?

I see that using strict: false and Schema.Types.Mixed is advised. however, I can't figure out... What I have tried:

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

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

Any tips? Thanks in advance!

Carlie answered 27/1, 2015 at 8:54 Comment(0)
D
59

Apply the strict: false option to your existing schema definition by supplying it as a second parameter to the Schema constructor:

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

If you want to leave feeds as fully schemaless, that's where you can used Mixed:

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

module.exports = mongoose.model('appForm', appFormSchema);
Diapositive answered 27/1, 2015 at 14:9 Comment(4)
That code works and posts default form data:user_id,LogTime and feeds array and its object but as I add another property into feeds array like:customText, it doesn't update that customText but the rest...I ll search where I am still doing something wrong..thanks anyway!Carlie
If you want to add arbitrary properties to feeds, then the option needs to be set on that embedded schema as well. See the updated answer.Diapositive
YES!!!:) second option is exactly what I am trying to do for hours! Thanks a lot!Carlie
@Diapositive can you please help and tell how to write a schema for inserting the json data into such appFormSchema ? I mean i am sending such complex json from my app to server, where rest api uses my predefined model schema to insert the data .Thing is while inserting i have diff number of json object in the feeds array so how to map them in db?Vapid
F
1

In the latest version of Mongoose, you can use something like this

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

we can set propertyName and it's type

Eg:

propertyName = "age"
propertyType = "Number"

addDynamicField(propertyName, propertyType);

This will create a dynamic property in the schema and also there is no need of using {strict: false}.

Funk answered 29/2 at 6:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.