Search code examples
jsonnode.jsmongodbmongooseschemaless

Create schemaless collection in mongoDB via mongoose


I have the following mongoose schema records:

var mongoose = require('mongoose');

module.exports = mongoose.model('lM', {
    any     :   mongoose.Schema.Types.Mixed,
},'mlr');

And in my code I am doing as such:

var lm      = require('../server/models/records');

new lm().save(lmr);

Being that lmr is a JSON object.

This produces a mongodb database with the name I provided but the records inside that collection contain only:

_id: objectID
_v: 0

The JSON objects is nowhere to be seen. How can I get the JSON object inside the any wrapper in the schema?


Solution

  • var lm      = require('../server/models/records');
    
    new lm({'any':lmr}).save();
    

    In save() method pass callback function[optional] if you want to track error if any.

    new lm({'any':lmr}).save(function(err){
       if(err) {
          console.log(err) 
       }else{
          console.log('saved')
       }
    });
    

    To create the schemaless collection you will have to set strict:false which is by default true. strict option ensures values passed to your model constructor that were not specified in schema do not get saved to the db.

    strict option docs