简体   繁体   中英

Mongodb dynamic schema to save any data

We often define a schema like this

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

var Account = new Schema({
    username: String,
    password: String
});

module.exports = mongoose.model('account', Account);

And we have to pass in object that matches the schema otherwise nothing worked. But says I want to save something that's dynamic, and I don't even know what are them for example it can be

{'name':'something',birthday:'1980-3-01'}

or just anything else

{'car':'ferrari','color':'red','qty':1}

How do you set the schema then?

You can use strict: false option to your existing schema definition by supplying it as a second parameter in Schema constructor:

Example

var AccountSchema = new Schema({
    Name : {type: String},
    Password : {type: String}
}, {strict: false});

module.exports = mongoose.model('Account', AccountSchema);

You can also use Mixed type

var TaskSchema = new Schema({
   Name : {type: String},
   Email : {type: String},
    Tasks : [Schema.Types.Mixed]
}, {strict: false});

module.exports = mongoose.model('Task', TaskSchema);

Mongoose has a Mixed schema type that allows a field to be any object.

var Account = new Schema({
    username: String,
    password: String,
    anyobject: Schema.Types.Mixed
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM