node.js - mongo insert in nodejs for loop only inserting one from array -
im building application collect votes live event.
the api doesnt give option select users time frame im polling endpoint every second.
i have 13 entries return endpoint, parse them , array , loop around them setting mongoose schema attributes , trying save them, when
db.votes.count() result 1
my node module looks like
var express = require('express'); var unirest = require('unirest'); var voteschema = require(global.rootdir + '/modules/voting/models/votes'); var seconds = 0; var interval = 1000; express({ votepoller : setinterval(function () { seconds++; if (typeof global.accesstoken != 'undefined') { var request = unirest.get('https://api.domain.io/api/v1/guests'); request .header('accept', 'application/json') .header('content-type', 'application/json; charset=utf-8') .header('authorization', 'bearer ' + global.accesstoken) .end(function (response) { if(response.code === 200){ var votesmodel = new voteschema; var payloadarray = json.parse(response.raw_body); for(var in payloadarray.guests){ console.log(i); console.log(payloadarray.guests[i]); votesmodel.ctid = payloadarray.guests[i].id; votesmodel.email = payloadarray.guests[i].username; votesmodel.votestatus = 0; votesmodel.createdat = new date(1000 * payloadarray.guests[i].created_at); votesmodel.save(function(err) { if (err) { console.log(err); console.log({ message: err }); } else { console.log({ message: 'vote saved' }); } }); console.log('done'); } } }); } console.log(seconds); }, interval) }); var votepoller = express; module.exports = votepoller;
my mongoose model is
var mongoose = require('mongoose'); var schema = mongoose.schema; var votesschema = new schema({ ctid: { type: string, required: true, unique: true }, fullname: { type: string}, email: { type: string, required: true, unique: true }, mobilenumber: { type: string }, vote: { type: number}, votestatus: boolean, createdat: date }); var votes = mongoose.model('votes', votesschema); module.exports = votes;
the console log counts out each in array why save function isn't being fired stumping me
thanks in advance
you need use async function async loop, there many answer on here code. suggest control flow library async or if using new version of node, use native promises instead. promises method best way achieve this.
Comments
Post a Comment