I want to perform a very simple action: clear the collection and insert a packet of data into it, but for a few days already nothing comes out, I ask for help. Initially tried using mongoose:

model.remove({}, (err, docs) => { if (err) { console.log('remove error'); } else { console.log('remove success'); model.insertMany(seeds, (insertError, insertedRecords) => { if (insertError) { console.log('insert error'); } else { console.log('insert success'); } }); } }); 

I see on the console only remove success . Then I tried using the driver:

 model.collection.remove((removeError, removeResult) => { console.log('remove cb'); model.collection.insert(seeds, (insertError, insertedRecords) => { console.log('insert cb'); }); }); 

Also see only remove cb

The Mongoose scheme is:

 const schema = new Schema({ name: {type: String, unique: true, index: true}, }); 

Inserted data:

 export default [ {name: 'USA'}, {name: 'Germany'}, {name: 'France'}, ... 

UPDATE1

I tried async.js , the result is the same:

  async.series([ (cb) => { console.log('remove serie'); model.remove({}, (err) => { console.log('remove cb'); cb(err); }); }, (cb) => { console.log('insert serie'); model.insertMany(seeds, (err) => { console.log('insert cb'); cb(err); }); } ], (err) => { console.log('err'); }); 

In console remove serie remove cb insert serie

  • async.series - first one action, then another. Even the "series" will not be: an array from a single delete function and an insert in a callback. The standard alternative is Promise: the result (empty collection) is passed as an argument to resolve (...) and to .then (... => again, the collection is turned to (already empty) and the new data is inserted into it. Although even async is better. parallel - when the deletion is completed, nothing is transferred to the callback, but it is simply called - it simply adds new data, the thing is two separate calls to the collection (and not one to the other) - Yuriy Po

1 answer 1

The collection was Bobik and Sharik - went straight to the database (in FAR) and was convinced. Corrected this code, like this:

 var async = require('async'); var mongoose = require('mongoose'); var Dogs = require('./models/Dogs'); var arrDogs = [{ name: 'Барбос', slug: 'barbos', age: 8 }, { name: 'Букет', slug: 'buket', age: 7 }]; async.parallel([ function(callback) { Dogs.remove({}, (err) => { if(err) console.error(err); }); callback(); }], () => { Dogs.insertMany(arrDogs, (err, data) => { if(err) console.error(err); console.log(data); }); mongoose.disconnect(); }); 

Launched in the console Sublime Text wrote:

 [ { __v: 0, name: 'Барбос', slug: 'barbos', age: 8, _id: 58e0af2c0bfd730f0868fc64 }, { __v: 0, name: 'Букет', slug: 'buket', age: 7, _id: 58e0af2c0bfd730f0868fc65 } ] 

[Finished in 1.0s]

And even (which is too much) went into the database - now there are two other documents: Barbosa and Bouquet.

  • I deleted 3 of your answers. Please transfer all the valuable ones into one answer. - PashaPash