jeudi 26 février 2015

Updating the result returned by find() method alone in Node.js using Mongoose

I am a newbie to Node.js. My Node.js application has a model called Selfie.



# model/selfie.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
selfieSchema = new Schema({
path: { type: String },
caption: { type: String },
sent_mod: { type: Number, default: -1 }, // -1 not sent, 0 sent, 1 accepted
display_count: { type: Number, default: -1 }, // -1 not sent, 0 sent, 1 displayed
time_stamp: { type: Date, default: new Date() }
}),
Selfie = mongoose.model('selfie', selfieSchema);

module.exports = Selfie;


Am breaking down the problem as follows:



  1. Retrieve 20 selfies whose mod_sent is -1.

  2. Update the mod_count of those 20 selfies to 0.


To retrieve 20 selfies am using find(), limit() and then exec() method. Once I have those selfies I can use forEach() and update() to iterate and update each of their sent_mod to 0. But this approach performs update operation 20 times. I think there might be a better way to do it. I read about findAndUpdate() from MongoDB documentation and found out that Mongoose has various methods like findOne(), findOneAndUpdate(). But am unable to find a better way to solve my problem using those methods also.



# routes/selfie.js
var express = require('express'),
router = express.Router(),

Selfie = require('../models/selfie'),

mongoose = require('mongoose');

router.get('/moderate', function(req, res) {

Selfie.find({ sent_mod: -1 }).limit(2).exec(function(err, selfies) {
if(err) {
console.log(err);
return;
}
console.log(selfies);

});
});


module.exports = router;

Aucun commentaire:

Enregistrer un commentaire