For some reason, whenever I create a new user in the database, it tries to add another user before and then errors out.
I am using Yeoman's generator angular-fullstack to create an api for my application. In this last week, I started noticing that when my database was populating, it did not display "finished populating users", signifying that it is not successfully adding users in my seed.js file. Here is my seed.js file.
Seed.js
'use strict';
var Thing = require('../api/thing/thing.model');
var User = require('../api/user/user.model');
var Item = require('../api/item/item.model');
var Calendar = require('../api/calendar/calendar.model');
Thing.find({}).remove(function() {});
User.find({}).remove(function() {
User.create({
provider: 'local',
role: 'student',
name: 'Student',
email: 'student#test.com',
password: 'test',
pin: '0807'
}, {
provider: 'local',
role: 'teacher',
name: 'Teacher',
email: 'teacher#test.com',
password: 'test',
pin: '0807'
}, {
provider: 'local',
role: 'admin',
name: 'Admin',
email: 'admin#admin.com',
password: 'admin',
pin: '0807'
}, function() {
console.log('finished populating users');
}, function(err) {
console.log(err);
});
});
Calendar.find({}).remove(function() {});
console.log("Removed Calendars");
Item.find({}).remove(function () {
Item.create({
calendarId: "dd7sfasd8f8sd",
title: "title",
description: "description",
date: new Date(),
checklists: [],
attachments: [],
status: "Not Completed",
edit: false,
verification: "test", //This will not be here in the long run
verify: false
}, {
calendarId: "323k3k2l23lk4j4",
title: "other",
description: "description",
date: new Date(),
checklists: [],
attachments: [],
status: "Completed",
edit: false,
verification: "test", //This will not be here in the long run
verify: false
}, {
calendarId: "323k3k2l23lk4j4",
title: "title",
description: "description",
date: new Date(),
checklists: [],
attachments: [],
status: "Verified",
edit: false,
verification: "test", //This will not be here in the long run
verify: false
}, {
calendarId: "323k3k2l23lk4j4",
title: "test",
description: "description",
date: new Date(),
checklists: [],
attachments: [],
status: "Not Completed",
edit: false,
verification: "test", //This will not be here in the long run
verify: false
}, function() {
console.log('finished populating items');
}
);
});
When I added the function when an error occurred, it displayed this:
Express server listening on 9000, in development mode
Done waiting!
Running "open:server" (open) task
Running "watch" task
Waiting...
{ _id: 5704a4d8b414a48822cd30a6, students: [], role: 'teacher' }
[Error: Invalid or no password]
finished populating items
As you might notice, the object displaying as the user to add is not the users in my seed.js file. To save time in looking through my entire model, here is the method where I am printing that user being created and where this error is occuring:
UserSchema
.pre('save', function(next) {
if (!this.isNew) return next();
console.log(this);
if (!validatePresenceOf(this.hashedPassword) && authTypes.indexOf(this.provider) === -1) {
next(new Error('Invalid or no password'));
if (!validatePresenceOf(this.hashedPin))
next(new Error('Invalid pin'));
} else {
next();
}
});
However, for more information into this error, I have the whole file shown below:
user.model.js
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var crypto = require('crypto');
var authTypes = ['github', 'twitter', 'facebook', 'google'];
var Student = new Schema({
firstName: String,
lastName: String,
age: Number
});
var UserSchema = new Schema({
name: String,
username: String,
email: { type: String, lowercase: true },
role: {
type: String,
default: 'teacher'
},
teachersEmail: { type: String, lowercase: true },
students: [Student],
status: String,
hashedPassword: String,
hashedPin: String,
hasPassword: Boolean,
provider: String,
salt: String,
pinSalt: String,
facebook: {},
twitter: {},
google: {},
github: {}
});
/**
* Virtuals
*/
UserSchema
.virtual('password')
.set(function(password) {
this._password = password;
this.salt = this.makeSalt();
this.hashedPassword = this.encryptPassword(password);
})
.get(function() {
return this._password;
});
UserSchema
.virtual('pin')
.set(function(pin) {
this._pin = pin;
this.pinSalt = this.makeSalt();
this.hashedPin = this.encryptPin(pin);
})
.get(function() {
return this._pin;
});
// Public profile information
UserSchema
.virtual('profile')
.get(function() {
return {
'name': this.name,
'role': this.role
};
});
// Non-sensitive info we'll be putting in the token
UserSchema
.virtual('token')
.get(function() {
return {
'_id': this._id,
'role': this.role
};
});
/**
* Validations
*/
// Validate empty email
UserSchema
.path('email')
.validate(function(email) {
if (authTypes.indexOf(this.provider) !== -1) return true;
return email.length;
}, 'Email cannot be blank');
// Validate empty password
UserSchema
.path('hashedPassword')
.validate(function(hashedPassword) {
if (authTypes.indexOf(this.provider) !== -1) return true;
return hashedPassword.length;
}, 'Password cannot be blank');
// Validate empty pin
UserSchema
.path('hashedPin')
.validate(function(hashedPin) {
return hashedPin.length;
}, 'PIN cannot be blank');
// Validate empty pin
UserSchema
.path('hashedPin')
.validate(function(hashedPin) {
return hashedPin.length == 4;
}, 'PIN must be 4 characters in length');
// Validate email is not taken
UserSchema
.path('email')
.validate(function(value, respond) {
var self = this;
this.constructor.findOne({email: value}, function(err, user) {
if(err) throw err;
if(user) {
if(self.id === user.id) return respond(true);
return respond(false);
}
respond(true);
});
}, 'The specified email address is already in use.');
var validatePresenceOf = function(value) {
return value && value.length;
};
/**
* Pre-save hook
*/
UserSchema
.pre('save', function(next) {
if (!this.isNew) return next();
console.log(this);
if (!validatePresenceOf(this.hashedPassword) && authTypes.indexOf(this.provider) === -1) {
next(new Error('Invalid or no password'));
if (!validatePresenceOf(this.hashedPin))
next(new Error('Invalid pin'));
} else {
next();
}
});
/**
* Methods
*/
UserSchema.methods = {
/**
* Authenticate - check if the passwords are the same
*
* #param {String} plainText
* #return {Boolean}
* #api public
*/
authenticate: function(plainText) {
if (this.hashedPassword) {
return this.encryptPassword(plainText) === this.hashedPassword;
} else {
return !!(this.google || this.facebook);
}
},
verify: function(plainText) {
return this.encryptPin(plainText) === this.hashedPin;
},
/**
* Make salt
*
* #return {String}
* #api public
*/
makeSalt: function() {
return crypto.randomBytes(16).toString('base64');
},
/**
* Encrypt password
*
* #param {String} password
* #return {String}
* #api public
*/
encryptPassword: function(password) {
if (!password || !this.salt) return '';
var salt = new Buffer(this.salt, 'base64');
return crypto.pbkdf2Sync(password, salt, 10000, 64).toString('base64');
},
encryptPin: function(pin) {
if (!pin || !this.pinSalt) return '';
var pinSalt = new Buffer(this.pinSalt, 'base64');
return crypto.pbkdf2Sync(pin, pinSalt, 10000, 64).toString('base64');
}
};
module.exports = mongoose.model('User', UserSchema);
Finally, I decided to separately add users in my seed.js file to see what happens, like so...
User.find({}).remove(function() {
User.create({
provider: 'local',
role: 'student',
name: 'Student',
email: 'student#test.com',
password: 'test',
pin: '0807'
}, function() {
console.log('Added user');
}, function(err) {
console.log(err);
});
User.create({
provider: 'local',
role: 'teacher',
name: 'Teacher',
email: 'teacher#test.com',
password: 'test',
pin: '0807'
}, function() {
console.log('Added user');
}, function(err) {
console.log(err);
});
User.create({
provider: 'local',
role: 'admin',
name: 'Admin',
email: 'admin#admin.com',
password: 'admin',
pin: '0807'
}, function() {
console.log('Added user');
}, function(err) {
console.log(err);
});
});
Here is what the terminal displayed:
Running "watch" task
Completed in 2.258s at Wed Apr 06 2016 00:08:34 GMT-0600 (Mountain Daylight Time) - Waiting...
{ _id: 5704a7e2d85623902a78e1fc, students: [], role: 'teacher' }
[Error: Invalid or no password]
{ _id: 5704a7e2d85623902a78e1fe, students: [], role: 'teacher' }
[Error: Invalid or no password]
{ _id: 5704a7e2d85623902a78e200, students: [], role: 'teacher' }
[Error: Invalid or no password]
finished populating items
The main problem here, is that it is adding a user that I did not add. (I added three. the first one is named "Student". The terminal is showing a user with no name, no email, nothing. Keep in mind that when I add users through my signup screen, this does not happen. The user is added fine...
What could be causing this?
Related
I create a order schema which have two models; StudentConsessionSchema and consessionSchema
StudentConsessionSchema acquire the student model (student model contain the details about the student).
The other model consessionSchema acquire the StudentConsessionSchema (for acquiring the student details).
When I test it in postman to order it works but it's not able to get the student details in consessionSchema.
order schema:
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const StudentConsessionSchema = new mongoose.Schema({
student: {
type: ObjectId,
ref: "Student", //ref to the student model from another file
},
FullName: {
type: String,
},
addmissionNumber: {
type: String,
required: true,
trim: true,
maxlength: 8,
},
faculty: {
type: ObjectId, //ref to the faculty model from another file
ref: "Faculty",
required: true,
},
});
const StudentConsession = mongoose.model(
"StudentConsession",
StudentConsessionSchema
);
const consessionSchema = new mongoose.Schema(
{
student: [StudentConsessionSchema], //this returns [] empty array
consession_id: {},
fromStation: {
type: String,
required: true,
},
toStation: {
type: String,
default: "Dadar",
},
passType: {
type: String,
enum: ["I", "II"],
required: true,
},
ticketPeriod: {
type: String,
enum: ["Monthly", "Quarterly"],
default: "Monthly",
required: true,
},
status: {
type: String,
default: "Pending",
enum: ["Pending", "Cancelled", "Accepted", "Printed"],
},
updated: Date,
},
{ timestamps: true }
);
const Consession = mongoose.model("Consession", consessionSchema);
module.exports = { StudentConsession, Consession };
create order controller:
exports.createOrder = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields) => {
const {
admissionNumber,
fullName,
faculty,
fromStation,
toStation,
passType,
ticketPeriod,
} = fields;
if (
!admissionNumber ||
!fullName ||
!faculty ||
!fromStation ||
!toStation ||
!passType ||
!ticketPeriod
) {
return res.status(400).json({
error: "Please fill all fields",
});
}
let consession = new Consession(fields);
// const consession = new Consession(req.body.consession);
if (req.student.pass === 1) {
return res.status(400).json({
error:
"You are not eligible to make request Because You already have a pass",
});
}
consession.save((err, order) => {
if (err) {
console.log(err);
return res.status(400).json({
error: "Failed to make order",
});
}
res.json(order);
});
});
};
output:
{
"toStation": "abc",
"ticketPeriod": "Monthly",
"status": "Pending",
"_id": "600e789887b9a201bc4c2d1a",
"fromStation": "xyz",
"passType": "II",
"student": [],
"createdAt": "2021-01-25T07:51:52.091Z",
"updatedAt": "2021-01-25T07:51:52.091Z",
"__v": 0
}
My questions is why is the student array empty?
When I am trying to update a document in my model, the .update() is returning null but the .find() method works fine.
module.exports.updateBio = function(req, res) {
var userID = req.params.id;
var objForUpdate = {};
if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.profile_picture = req.body.profile_picture;
if (!troolr.isEmptyString(req.body.title)) objForUpdate.title = req.body.title;
if (!troolr.isEmptyString(req.body.intro)) objForUpdate.intro = req.body.intro;
if (!troolr.isEmptyString(req.body.summary)) objForUpdate.summary = req.body.summary;
if (!troolr.isEmptyString(req.body.skills)) objForUpdate.skills = req.body.skills;
if (!troolr.isEmptyString(req.body.facebook)) objForUpdate.social.facebook = req.body.facebook;
if (!troolr.isEmptyString(req.body.twitter)) objForUpdate.social.twitter = req.body.twitter;
if (!troolr.isEmptyString(req.body.linkedin)) objForUpdate.social.linkedin = req.body.linkedin;
if (!troolr.isEmptyString(req.body.website)) objForUpdate.social.website = req.body.website;
var conditions = { "_id": userID }
, setObj = { $set: objForUpdate }
, options = { multi: true };
//This throws error
// Error: { ok: 0, n: 0, nModified: 0 }
Profile.update(conditions, setObj, (err, page) =>{
if(err) throw err;
console.log(page);
});
// This works fine but it erases old values if they are empty
/* Profile.findById(userID, (error, user) => {
if(error) return res.status(500).json({ success: false, error: error });
user.bio = objForUpdate;
user.save(function(error) {
if(error) return res.status(500).json({ success: false, error: error });
return res.status(200).json({ success: true, message: "Bio successfully updated." });
});
}); */
};
// API Endpoint
http://localhost:3000/api/v1/profile/592c53b3bdf350ce004ad717/updatebio
// API Define
'use strict';
/**
* Routes for Profile Model
*
**/
var passport = require('passport');
var jwt = require('jwt-simple');
var settings = require("settings");
var profileCtrl = require(settings.PROJECT_DIR + 'routes/controllers/api/profile');
module.exports = function(app) {
app.get('/all', profileCtrl.getAll);
app.get('/:id', profileCtrl.getSingle);
app.put('/:id/updateurl', profileCtrl.updateURL);
app.put('/:id/updateaddress', profileCtrl.updateAddress);
app.put('/:id/updatebio', profileCtrl.updateBio);
}
// Model
var mongoose = require('mongoose');
// User Schema
var ProfileSchema = mongoose.Schema({
url : {
type: String,
unique: true,
},
fname: {
type: String,
required: true
},
lname: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true
},
bio: {
profile_picture: {
type: String
},
title: {
type: String
},
intro: {
type: String
},
summary: {
type: String
},
skills: {
type: Object
},
social: {
linkedin: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
website: {
type: String
}
},
},
location: {
address: {
type: String
},
apt: {
type: String
},
city: {
type: String
},
state: {
type: String
},
zip_code: {
type: String
},
country: {
type: String
}
},
phone: {
type: Number
},
listings: {
type: Object
},
reviews: {
type: Object
},
verfied: {
type: Boolean,
default: false
},
// expires: {
// type: Date,
// expires: '1h',
// default: Date.now
// },
});
var Profile = module.exports = mongoose.model('Profile', ProfileSchema);
module.exports.getUserByEmail = function(email, callback){
var query = {'email': email};
Profile.findOne(query, callback);
}
module.exports.checkIfUrlExists = function(res, url, callback){
var query = {'url': url};
Profile.findOne(query, function(error, found) {
if(error) return res.status(500).json(error);
if(found) return res.status(500).json({success: false, message: "URL already exists" });
if(callback) callback();
});
}
// Document which I am trying to update
{
"_id": "592c53b3bdf350ce004ad717",
"url": "hyoh7ryb-",
"fname": "Foo",
"lname": "Bar",
"email": "foobar#gmail.com",
"__v": 0,
"verfied": false
}
Anything not defined in schema is not saved. That's what happening when you're missing bio key while preparing the objForUpdate to $set:
var objForUpdate = {};
if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.profile_picture = req.body.profile_picture;
which should be
var objForUpdate = {
bio: {}
};
if (!troolr.isEmptyString(req.body.profile_picture)) objForUpdate.bio.profile_picture = req.body.profile_picture;
if (!troolr.isEmptyString(req.body.title)) objForUpdate.bio.title = req.body.title;
// and so on
Your save is working because of saving the object in the right keyuser.bio = objForUpdate;
The following piece of code which works fine. However,when I run it again from my cmd(node server),I get a duplicate key message of the dish name. I have two files. The dishes.js where I define my schemas and make available to my second file called server.js.
dishes
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var commentSchema = new Schema({
rating: {
type: Number,
min: 1,
max: 5,
required: true
},
comment: {
type: String,
required: true
},
author: {
type: String,
required: true
}
}, {
timestamps: true
});
// create a schema
var dishSchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
description: {
type: String,
required: true
},
comments:[commentSchema]
},
{
timestamps: true
});
// the schema is useless so far
// we need to create a model using it
var Dishes = mongoose.model('Dish', dishSchema);
// make this available to our Node applications
module.exports = Dishes;
and my server.js file.
var mongoose = require('mongoose'),
assert = require('assert');
var Dishes = require('./models/dishes-3');
// Connection URL
var url = 'mongodb://localhost:27017/conFusion';mongoose.connect(url);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
// create a new dish
Dishes.create({
name: 'Uthapizza',
description: 'Test',
comments: [
{
rating: 3,
comment: 'This is insane',
author: 'Matt Daemon'
}
]
}, function (err, dish) {
if (err) throw err;
console.log('Dish created!');
console.log(dish);
var id = dish._id;
// get all the dishes
setTimeout(function () {
Dishes.findByIdAndUpdate(id, {
$set: {
description: 'Updated Test'
}
}, {
new: true
})
.exec(function (err, dish) {
if (err) throw err;
console.log('Updated Dish!');
console.log(dish);
dish.comments.push({
rating: 5,
comment: 'I\'m getting a sinking feeling!',
author: 'Leonardo di Carpaccio'
});
dish.save(function (err, dish) {
console.log('Updated Comments!');
console.log(dish);
db.collection('dishes').drop(function () {
db.close();
});
});
});
}, 3000);
});
});
If you pay a close attention in the server.js file I have removed the unique: true attribute from by dishes.js file,but I still have the same problem.
name: {
type: String,
required: true,
unique: true
},
when your schema is given below
name: {
type: String,
required: true,
unique: true
}
the unique is working
when your schema is given below
name: {
type: String,
required: true
}
the unique not working
after change your schema definition, drop all your collection and try to insert.
Im currently stuck at a problem within my router.
I export the function as you see in the following code.
This is my Model:
"use strict";
var mongoose = require('mongoose');
var bcrypt = require("bcryptjs");
var Schema = mongoose.Schema;
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
gender: {
type: String,
required: true
},
country: {
type: String,
required: true
},
confirm: {
type: Number
},
confirmcode: {
type: String
},
ip: {
type: String
},
signup: {
type: Date,
default : Date.now
},
voice: {
type: String
},
steam: {
type: String
},
steamid: {
type: String
},
steamlink: {
type: String
},
battletag: {
type: String
},
showsteam: {
type: Number
},
showbnet: {
type: Number
},
birthdate: {
type: Date,
required: true
},
language: {
type: String
}
});
var User = module.exports = mongoose.model('User',UserSchema);
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
module.exports.comparePw = function(canPw, hash, callback){
bcrypt.compare(canPw, hash).then((res) => {
callback(null,res);
});
}
module.exports.findUserById = function(id,callback){
User.findById(id,callback);
}
module.exports.getGamer = function(count,callback){
User.count(count,callback);
}
module.exports.findUsername = function(uname, callback){
var query = {username:uname};
User.findOne(query,callback);
}
module.exports.findEmail = function(email, callback){
var query = {email:email};
User.findOne(query,callback);
}
This is my Router:
var User = require("../../model/user");
module.exports = function(router){
router.get("/user", function(req, res){
var user = new User();
user.getGamer(function(err,response){
if(err){
throw err;
}else{
res.json(response);
}
});
});
}
the error i get is:
TypeError: user.getGamer is not a function
But i dont know why. Anyone can help me ?
You need to attach model methods to the schema, not to the model. Then the methods will be available on instances of your model. See this post for more.
UserSchema.methods.getGamer = function(newUser, callback) ...
I have 400,000 lines to enter and I need to break it up. Unfortunately I cannot get this script to exit until it's completed everything. It invariably runs out of memory of course. I thought setting a value at .on('end',function() would be useful but I can't see that value once the .on data has completed.
'use strict';
var mongoose = require('mongoose');
var fs = require('fs');
var parse = require('csv-parse');
var Schema = mongoose.Schema;
var done;
mongoose.connect('mongodb://127.0.0.1:27017/auth');
var userSchema = new mongoose.Schema({
username: {
type: String,
unique: true
},
password: String,
email: {
type: String,
unique: true
},
isActive: String,
roles: {
account: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Account'
}
},
timeCreated: {
type: Date,
default: Date.now
},
search: [String]
});
var accountSchema = new mongoose.Schema({
user: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
name: {
type: String,
default: ''
}
},
isVerified: {
type: String,
default: ''
},
verificationToken: {
type: String,
default: ''
},
name: {
first: {
type: String,
default: ''
},
middle: {
type: String,
default: ''
},
last: {
type: String,
default: ''
},
full: {
type: String,
default: ''
}
},
company: {
type: String,
default: ''
},
phone: {
type: String,
default: ''
},
zip: {
type: String,
default: ''
},
memberid: {
type: String,
default: ''
},
status: {
id: {
type: String,
ref: 'Status'
},
name: {
type: String,
default: ''
},
userCreated: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
name: {
type: String,
default: ''
},
time: {
type: Date,
default: Date.now
}
}
},
userCreated: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
name: {
type: String,
default: ''
},
time: {
type: Date,
default: Date.now
}
},
search: [String]
});
var User = mongoose.model('User', userSchema);
var Account = mongoose.model('Account', accountSchema);
fs.createReadStream('./ipart')
.pipe(parse({
delimiter: ','
}))
.on("data-invalid", function(data) {})
.on('data', function(csvrow) {
var u = {
isActive: 'yes',
username: csvrow[0],
email: csvrow[0],
search: [
csvrow[1] + ' ' + csvrow[2],
csvrow[0],
]
};
User.create(u, function(err, createdUser) {
if (err) {
console.log(err);
return;
}
var user = createdUser;
var displayName = csvrow[1] + ' ' + csvrow[2] || '';
var nameParts = displayName.split(' ');
var acct = {
isVerified: 'no',
'name.first': nameParts[0],
'name.last': nameParts[1] || '',
'name.full': displayName,
user: {
id: user._id,
name: user.username
},
search: [
nameParts[0],
nameParts[1] || ''
]
};
Account.create(acct, function(err, account) {
if (err) {
return workflow.emit('exception', err);
}
var fieldstoset = {
roles: {
account: account._id
}
};
User.findByIdAndUpdate(account.user.id, fieldstoset, function(err, user) {
if (err) throw err;
});
});
});
})
.on('end', function() {
console.log('complete');
});
You really need to use bulk inserts, I found this code somewhere and pasting it for you
var Potato = mongoose.model('Potato', PotatoSchema);
var potatoBag = [/* a humongous amount of potato objects */];
Potato.collection.insert(potatoBag, onInsert);
function onInsert(err, docs) {
if (err) {
// TODO: handle error
} else {
console.info('%d potatoes were successfully stored.', docs.length);
}
}
I would recommend you to break down your entire logic of importing your CSV data into these following steps:
1. Write a simple script file which imports the CSV into a temporary collection like this:
YourImportScript
#!/bin/bash
mongoimport -d YourDBName -c YourTempCollectionName --drop --type csv --file pathToYourCSVFile.csv --headerline
2. Run the scripts before creating your Users:
var exec = require('child_process').exec;
function importCSV(callback) {
exec("./pathToYourImportScript/YourImportScript", function (error, stdout, stderr) {
console.log(stdout);
if (error !== null)
console.log('exec error: ' + error);
});
callback()
}
MongoImport will import the CSV pretty quickly.
Get the documents from the temp collection and insert them into your Users Collection.
You can also use async module to control the flow of your code mode neatly:
async.series([
function (callback) {
//CSV Import function
},
function (callback) {
//User Manupulation function
}]);
And it is better to put headers into your CSV columns, as you can create a model when importing documents from the temp collections, and it would be easier to get the properties of users by column headers like username:myCSVModel.username instead of username: csvrow[0].