0

In my script i can create a new collection in mongodb but default one empty record is inserting so how to avoid that.

model.js:

 /* model.js */
 'use strict';

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


 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String
    }

   }); 
   return mongoose.model(suffix, addressSchema); 
  } 
  module.exports = dynamicModel;

data.controller.js:

      var NewModel = require(path.resolve('./models/model.js'))(collectionName);
      NewModel.create({ category: 1, title: 'Minion' }, function(err, doc) {

      });

after created new collection I am seeing like this:

  _id:ObjectId("5eceb362d538901accc0fefe");
  __v:0
3
  • 1
    category and title attributes are not available in your Schema, that's why it's creating a collection with only _id and __v. Commented May 28, 2020 at 12:43
  • @Vishnu: So can i remove category and title? Commented May 28, 2020 at 13:08
  • 1
    The strict option is by default enabled in Schema. If you need to add extra fields that are not specified in Schema you can set the strict option to false. mongoosejs.com/docs/guide.html#strict Commented May 28, 2020 at 13:33

1 Answer 1

1

You must define these attributes in your model.

 /* model.js */
 'use strict';

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


 function dynamicModel(suffix) {
   var addressSchema = new Schema({

    product_name: {
        type: String,
    },
    category: {
       type: Number,
    },
    title: {
       type: String,
    }

   }); 
   return mongoose.model(suffix, addressSchema); 
  } 
  module.exports = dynamicModel;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.