1

I have connected with MongoDB using below code.

mongoose.connect('mongodb://localhost:27017/samplecustomfields')
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));

I have created the schema model and load model in my app.js file. You can see below code

const customfields = [
{
  'id': 104,
  'name': '[Sample] Utility Caddy',
  'customfields': [
      {
          'id': 7,
          'product_id': 104,
          'name': 'Sample Utility',
          'text': 'canddy ofsuc'
      }
 }
]
require('./models/customfieldlists');
const productfields = mongoose.model('fields');

app.get('/api/products', (req, res, next) => {
productfields.insertMany(customfields, function(error, docs) {
  console.log('done');
});
res.send(customfields);
});

How can I drop my "fields" collection first and after call "insertMany" query. This should happend everytime when I get the '/api/products' this request.

I have put the code "productfields.dropCollection('fields');" above insertMany query but it does not work.

Ankit Parmar
  • 670
  • 10
  • 24

2 Answers2

1
app.get('/api/products', (req, res, next) => {
    // Drop the 'fields' collection from the current database
    mongoose.connection.db.dropCollection('fields', function(err, result) {
         productfields.insertMany(customfields, function(error, docs) {
         console.log('done');
         res.send(customfields);
         });
    )};
});

I hope this will help you.

1

I have found from below URL that there is no method for dropping a collection using mongoose, but you can remove the data from the collection.

How to drop a database with Mongoose?

Here is below code to solve my question

productfields.remove({}, function(err) {
    productfields.insertMany(customfields, function(error, docs) {
        res.send(docs);
     });
});
Ankit Parmar
  • 670
  • 10
  • 24