0

I have a collection named Article in MongoDB database, with the following schema and model:

var articleSchema = new Schema({
   site: String,
   date: String, 
   day: String, 
   link: {
    type: String,
    unique: true,
    index: {unique:true}    
 });

var Article = mongoose.model('Article', articleSchema);

An example of document, which has no day field yet:

[ { site: 'www.atlantico.fr',
    date: '2014-05-27T11:10:19.000Z',
    link: 'http://www.atlantico.fr/example.html',
    _id: 538473817eb00f082f4803fc,
    __v: 0} ]

I want, for all the documents of this collection, to update the day field, depending on the date field (in a given way that I know).

I tried that:

Article.find() // all documents
.exec(function (err, articles) { // articles is an array

    for (var i=0; i<articles.length; i++) { // for each document

        var myDate = articles[i].date; // I take its date
        myDate = myDate.replace(/^(\d{4})\-(\d{2})\-(\d{2}).*$/, '$3/$2/$1'); // I create a new variable 

        Article.update({date: articles[i].date}, // articles with this date
                       {day : myDate }, // update with the new variable created using the date
                       function(err, numberAffected){  
        });                           
      }
});

If I run this code for a given document (by putting a condition like {link: 'http://www.atlantico.fr/example.html'} in Article.find(), it works.

But if run the code showed above, that is supposed to do the job for all the documents, there must be a problem, because then I can see that all the documents have not been updated.

What am I missing? Thank you for your help.

GBC
  • 345
  • 3
  • 8
  • 23

2 Answers2

1

You can't refer to the fields in the document when updating. The answer you have posted seems to be the way to go. Refer to this answer Update MongoDB field using value of another field

Community
  • 1
  • 1
ma08
  • 3,654
  • 3
  • 23
  • 36
0

I read http://mongoosejs.com/docs/2.7.x/docs/updating-documents.html and I tried this:

Article.find({}, function (err, articles) {    
    for (var i=0; i<articles.length; i++) {            
        Article.findOne({ link: articles[i].link }, function (err, doc){
            doc.day = doc.date.replace(/^(\d{4})\-(\d{2})\-(\d{2}).*$/, '$3/$2/$1');
            doc.save();
        });      
     }  
});

It seems to work.

But I don't know if it is the best solution.

GBC
  • 345
  • 3
  • 8
  • 23