I'm passed an object_id and an array of new descriptions.
I'm trying to take a single document and clone it x number of times based on descriptions.length. For each cloned object I want to set the description based on the array value, create a new ObjectId() for the new document and assign a unique key based on the exiting documents.
This is what I've used to get the max value from the database:
doc.findOne({'doc_id': new RegExp('^' + doc.type + '[0-9]+')}, '_id doc_id')
.sort({doc_id: 1 / -1}).limit(-1)
.exec(function (err, maxDoc)... //returns maxDoc.doc_id + 1
The issue that I can't seem to figure out is timing on the save. The call to get the max doc_id is run asynchronously and the max_id is the same for all of the documents. What am I missing here?
First step is to find the doc with the object_id
In controller
exports.clone = function (req, res) {
var id = req.body.id;
var decs = req.body.target_descs;
doc.findById(id).exec(function (err, existingDoc) {
if (err) {
return res.jsonp(500, {
error: 'Cannot find record'
});
}
if (!existingDoc) {
return res.jsonp(404, {
error: 'Failed to find with id of: ' + id
});
}
This works fine. At this point I've tried using for loop on descs, pre functions within save, and other assorted call backs.
for(var index = 0; index < descs.length; i++){
var newDoc = new Doc(existingDoc);
newDoc._id = mongoose.Types.ObjectId();
newDoc.desc = descs[index];
newDoc.save(function (err, newDoc){
if(err){
console.log(err);
return res.jsonp(500, {error: err})
}
else{
console.log('saved correctly ' + newDoc);
}
})
}
In model
function getNextSequence(self, callback) {
if (!self) {
return 'Please Provide Type to search';
}
mongoose.models['Doc'].findOne({'doc_id': new RegExp('^' + self.type + '[0-9]+')}, '_id doc_id').sort({doc_id: 1 / -1}).limit(-1).exec(function (err, maxDoc){
console.log(maxDoc);
if (err) {
console.log(err);
callback(new Error('Cannot list the document'), null);
}
var numericPortion = parseInt(maxDoc.doc_id.match(/\d+/)[0]);
numericPortion += 1;
var doc_id = maxDoc.replace(/\d+/g, '') + numericPortion;
console.log('New Doc ID: ' + doc_id);
callback(null, doc_id);
});
}
masterSchema.pre('save', function (next) {
var self = this;
if(self.isNew===false)
{
console.log('DEBUG --- updating existing record');
next();
}
else
{
console.log('Creating a new Doc Record');
getNextSequence(self, function(err, newEgm_id) {
if (err) {
console.log(err);
self.invalidate('doc_id', 'doc_id must be populated');
return null;
}
console.log('New doc_id: ' + newdoc_id);
if(!newdoc_id)
{
self.invalidate('doc_id', 'doc_id must be populated');
next(new Error('doc_id must be populated')) ;
}
self.doc_id = newdoc_id;
});
next();
}
});