I want to increment the quantity count in my database everytime I click my button.
This is my angular directive:
var count = 0
$scope.postNote = function () {
var deferred = $q.defer()
var token = $scope.userInfo.$$state.value.accessToken
$scope.userInfo.$$state.value.cart.quantity.push(count += 1)
$http.put('/api/me/cart?access_token=' + token, $scope.userInfo.$$state.value)
.then(function (result) {
deferred.resolve(result)
}, function (err) {
deferred.reject(err)
})
return deferred.promise
}
This is my api:
router.put('/me/cart', wagner.invoke((User) => {
return (req, res) => {
try {
var cart = req.body.cart
} catch (e) {
return res.status(status.BAD_REQUEST)
.json({ error: 'Sorry, you have failed in life' })
}
req.user.data.cart = cart
req.user.save((err, user) => {
if (err) {
return res.status(status.INTERNAL_SERVER_ERROR)
.json({ error: err.toString() })
}
return res.json(user)
})
}
}))
Finally, this is how my document look:
"_id" : ObjectId("56ca4dc77aaab42f074250ba"),
"password" : "$2a$10$KnIVYcIjE/AYfUnMgkWhc.bQ1Luxo8XRUq/lnuPXKsOKR8YEz2m7O",
"username" : "ken",
"data" : {
"cart" : {
"quantity" : [
1,
2,
3,
4,
5
]
}
},
"__v" : 0
I just want the quantity element to increment everytime I click it.
I figured it out. I made the change in my directive.
var count = 0
$scope.postNote = function () {
var deferred = $q.defer()
var token = $scope.userInfo.$$state.value.accessToken
$scope.userInfo.$$state.value.cart.quantity = count++
$http.put('/api/me/cart?access_token=' + token, $scope.userInfo.$$state.value)
.then(function (result) {
deferred.resolve(result)
}, function (err) {
deferred.reject(err)
})
return deferred.promise
}
Related
I currently have the code below, which was created from a previous question I posted last year here.
var imaps = require('imap-simple');
var configBauerEmail = {
imap: {
user: '********#hotmail.com',
password: '******',
host: 'imap-mail.outlook.com',
port: 993,
tls: true,
authTimeout: 30000
}
};
module.exports = {
'delete any existing emails...': function () {
imaps.connect(configBauerEmail).then(function (connection) {
connection.openBox('INBOX').then(function () {
var searchCriteria = ['ALL'];
var fetchOptions = { bodies: ['TEXT'], struct: true
};
return connection.search(searchCriteria, fetchOptions);
})
//Loop over each message
.then(function (messages) {
let taskList = messages.map(function (message) {
return new Promise((res, rej) => {
var parts = imaps.getParts(message.attributes.struct);
parts.map(function (part) {
return connection.getPartData(message, part)
.then(function (partData) {
//Display e-mail body
if (part.disposition == null && part.encoding != "base64") {
console.log(partData);
}
//Mark message for deletion
connection.addFlags(message.attributes.uid, "\Deleted", (err) => {
if (err) {
console.log('Problem marking message for deletion');
rej(err);
}
res();
});
});
});
});
});
return Promise.all(taskList).then(() => {
connection.imap.closeBox(true, (err) => {
if (err) {
console.log(err);
}
});
connection.end();
});
});
});
},
'send email to seller and wait for mailbox notification': function (browser) {
browser.url(browser.launch_url + browser.globals.testDealerBfsAdevertEmailTest);
browser.notificationDismissal();
browser.cmpDismissal();
browser.emailFunctionality.emailTheSeller();
browser.browserEnd();
},
'get new email info': function() {
const createPromise = ms => new Promise((resolve, reject) => {
setTimeout(() => resolve(ms), ms);
});
function findUnseenEmails(connection) {
return connection.openBox('INBOX').then(function () {
var searchCriteria = ['UNSEEN'];
var fetchOptions = {
bodies: ['HEADER','TEXT'],
markSeen: false
};
return connection.search(searchCriteria, fetchOptions).then(function (results) {
var subjects = results.map(function (res) {
return res.parts.filter(function (part) {
return part.which === 'HEADER';
})
[0].body.subject[0];
});
console.log(subjects);
if (subjects.length > 0) {
connection.end();
return subjects;
} else {
return createPromise(60000).then(function() {
return findUnseenEmails(connection);
});
}
});
});
}
imaps.connect(configBauerEmail).then(function (connection) {
return findUnseenEmails(connection);
})
.then((subjects) => console.log('finished', subjects));
},
};
This works OK, in that the following loop that was added will loop over every 60 seconds checking that the email has 'arrived' in the mailbox.
if (subjects.length > 0) {
connection.end();
return subjects;
} else {
return createPromise(60000).then(function() {
return findUnseenEmails(connection);
});
}
});
However, at present if the email sending process has failed and the email account does not receive the email, the test will carry on looping continuously until the test is physically stopped.
What I'd now like to do is set some sort of 'time limit' within this loop, so that if the email has not arrived in the mailbox within 30 minutes the test will fail.
I appreciate that this will involve a limit setting in the loop above, but I've tried it in several locations within the loop and I can't get it to work.
Any help would be greatly appreciated. Thanks.
I'm trying to update this attached
Mongo collection using the following controller, but getting bad value mongoError. Should I need to change the Model or are any changes needed in the current controller?
updateMarkCard = (req, res) => {
const reg = "66";
const sem = "sem-1";
const Ia = "IA-1";
MarksCardList.find({ student_id: reg }).exec((err, data) => {
if (err) res.status(400).json({ message: "Student Not Found" });
if (data) {
const findSem = data[0].marksCard_list.find((el) => {
return el.semister === sem;
});
const findIA =
findSem &&
findSem.IA.find((el) => {
return el.IA_type === Ia;
});
MarksCardList.findOneAndUpdate(
{
student_id: reg,
"marksCard_list._id": findSem._id,
},
{
$set: {
"marksCard_list.$[marksCard_list].IA.$[IA].marks": req.body.marks,
},
},
{
arrayFilters: [
{ "marksCard_list._id": findSem._id },
{ "IA._id": findIA._id },
],
}
).exec((er, data) => {
if (er) res.status(400).json({ ...er });
if (data) res.status(400).json({ data });
});
}
});
};
req.body.courses has multiples id's of courses that I want to add to a specific categorie, the problem is that when my code runs it save a course more that one time, sometimes four or five times, depending on the number of loops it does.
The function:
router.post('/categories/:cat_id/', function (req, res) {
Categorie.findById(req.params.cat_id, function(err, categorie){
if(err){
console.log(err);
} else {
var courses = req.body.courses;
courses.forEach(function (course){
Course.findOne({ _id: course }, function(err, foundCourse) {
if(err){
console.log(err);
} else {
categorie.courses.push(foundCourse._id);
categorie.save();
}
});
});
}
});
return res.redirect('/dash');
});
The CategorieSchema:
var categorieSchema = mongoose.Schema({
name: String,
courses: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Course"
}
]
});
Here is an example of trying to add 4 courses to the categorie:
{ "_id" : ObjectId("5a871964a6b4820ecf7abaa7"), "courses" : [ ObjectId("5a870a7374486e0b0d69f710"), ObjectId("5a870a7a74486e0b0d69f711"), ObjectId("5a870a6974486e0b0d69f70f"),
ObjectId("5a870a7374486e0b0d69f710"), ObjectId("5a870a7a74486e0b0d69f711"), ObjectId("5a870a6974486e0b0d69f70f"),
ObjectId("5a870a7374486e0b0d69f710"), ObjectId("5a870a7a74486e0b0d69f711"), ObjectId("5a870a6974486e0b0d69f70f") ], "name" : "test2", "__v" : 3 }
Node.js Is async, It does not wait for the loop to execute completely and each time you are adding _id in existing array because of that adds 2-3 times.
Try this once I have not tested this.
const findOne = (course) => {
return new Promise((resolve, reject) => {
Course.findOne({
_id: course
}, (err, foundCourse) => {
if (err)
return reject(err);
return resolve(foundCourse._id);
});
});
}
router.post('/categories/:cat_id/', function (req, res) {
Categorie.findById(req.params.cat_id, function (err, categorie) {
if (err) {
console.log(err);
res.status(400).json(err);
} else {
var courses = req.body.courses;
Promise.all(courses.map((course) => {
return findOne(course);
})).then((data) => {
// check if course id already there skip
data = data.filter((course) => {
return !categorie.courses.includes(course);
});
categorie.courses = categorie.courses.concat(data);
categorie.save();
return res.redirect('/dash');
}).catch((err) => {
console.log(err);
res.status(400).json(err);
});
}
});
});
An alternative would involve a first query returning the courses using $in operator with Course.find() and then update the courses array in the Categorie model with Categorie.findByIdAndUpdate():
router.post('/categories/:cat_id/', function (req, res) {
Course.find({ '_id': { '$in': req.body.courses }}).exec((err, courses) => {
Categorie.findByIdAndUpdate(
req.params.cat_id,
{ '$addToSet': { 'courses': courses } },
{ 'new': true },
(err, categorie) => {
if (err){
console.log(err);
} else {
return res.redirect('/dash');
}
}
});
});
});
I created two collections,one for enterprise and another for employees,their schema is as follows,
var mongoose= require('mongoose');
var Enterprise= new mongoose.Schema({
name:{type:String},
email:{type:String},
sector:{type:String},
employees: {type:Number,default:0}
});
module.exports={
Enterprise:Enterprise
};
var mongoose = require('mongoose');
var employee = new mongoose.Schema({
enterprise:{type: String},
name:{type:String},
email:{type:String},
password:{type:String},
gender:{type:String},
});
module.exports = {
employee:employee
};
my add employee route,
var mongoose = require('mongoose');
var q = require('q');
var employee = mongoose.model('employee');
var enterprise = mongoose.model('enterprise');
var addEmployee = function(req, res) {
newEmployee = new employee();
newEmployee.enterprise = req.params.enterprise;
newEmployee.name = req.params.name;
newEmployee.email = req.params.email;
newEmployee.gender = req.params.gender;
function detailSave() {
var deferred = q.defer();
newEmployee.save(function(err, data) {
if (err) {
res.send(500);
console.log('couldnt save employee details');
deferred.reject({errmessage: 'couldnt save employee details', err: err});
} else {
res.send(200);
deferred.resolve({data: data});
}
});
return deferred.promise;
}
function incrementEmployee(doc) {
var deferred = q.defer();
enterprise.findOneAndUpdate({ 'name': doc.enterprise }, { $inc: { 'employees': 1 } },
function(err, num) {
if (err) {
deferred.reject({errmessage: 'couldnt incrementEmployee', err: err});
res.send(500);
console.log('couldnt incrementEmployee');
} else {
res.send(200);
deferred.resolve({num:num});
}
});
return deferred.promise;
}
detailSave()
.then(incrementEmployee)
.then(function(success) {
console.log('success', success);
res.json(200, success);
})
.fail(function(err) {
res.json(500, err);
})
.done();
};
module.exports = {
addEmployee: addEmployee
};
The problem is when I add an employee, the employees field in enterprise collection doesn't increment
I think your query is not working since doc.enterprise is null
On the basis of your comment.
Try to give your query like this {'name': doc.data.enterprise}
function incrementEmployee(doc) {
var deferred = q.defer();
enterprise.findOneAndUpdate({
'name': doc.data.enterprise
}, {
$inc: {
'employees': 1
}
},
function(err, num) {
if (err) {
deferred.reject({
errmessage: 'couldnt incrementEmployee',
err: err
});
res.send(500);
console.log('couldnt incrementEmployee');
} else {
res.send(200);
deferred.resolve({
num: num
});
}
});
return deferred.promise;
}
Why wont usernametoid function return the acual id? cause im trying to send the result of the userdata as the return. In this case, i want to only send the userdata`s _id attribute. but it seems like it wont work.
console.log(userdata._id); // works
return resolve(userdata._id); // wont work.
output of variable userdata:
{
cash: 7300002,
bank: 0,
xp: 0,
rank: 1,
points: 1,
location: 1,
health: 100,
protection: 1,
attack: 1,
family: '0',
password: 'jKa4qC7pRCgE5jvzD9Vv1pRUNxFlQEM7Jpq/IoJ/sUWOAv1Wx1RI/j/Vu6Zf8zyNkCFcg3QBtdfAC+lmPS8KIA==',
profileImageURL: 'modules/users/client/img/profile/default.png',
roles: [ 'user' ],
created: Sat Aug 27 2016 12:33:55 GMT-0400 (EDT),
__v: 0,
username: 'signature',
provider: 'local',
salt: '4ySlrr9ggESxBB3dR5bx4Q==',
_id: 57c1c0f3b6b20c011242bf22 }
when i do: `return resolve(userdata._id) it would get this error:
/server/factory/user_factory.js:52
return resolve(userdata._id);
^
TypeError: Cannot read property '_id' of null
node.js call:
var articles = require('../controllers/articles.server.controller'),
path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
Users = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
var userFunc = require('../factory/user_factory.js');
app.post('/api/kill', function (req, res) {
console.log("starting");
var username = "signature";//req.query.username;
var result = ["test service"];
var data = req.user;
userFunc.usernametoid(username).then( function (otherplayerid) {
if (!(otherplayerid)) {
console.log("other player is acually " + otherplayerid);
result.push("denne brukeren finnes ikke! " + otherplayerid);
} else {
userFunc.usernametoid(otherplayerid).then( function (otherplayer) {
if (data.location != otherplayer.location) {
result.push("Du er ikke i samme lokasjon som " + username);
result.push(data.location + " vs " + otherplayer.location);
} else {
userFunc.addCash(req.user._id,100000);
result.push("starter lokasjonisering");
}
});
}
res.json(result);
});
});
user factory:
var articles = require('../controllers/articles.server.controller'),
path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
Users = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
exports.usernametoid = usernametoid;
function usernametoid(id) {
return new Promise( function (resolve, reject) {
var query = Users.findOne( { username : id } );
// var query = Users.find({_id:id});
query.exec(function(err, userdata) {
if (err){
return reject({err : 'Error while getting user info'});
}
console.log(userdata._id);
return resolve(userdata);
});
}, function (){
return reject({err : 'error while fetching cash'});
});
}
Because you are not passing correctly the fetched user to the query.exec.
You need to do:
var Users = require('../models/users-model.js');
function usernametoid(id) {
return new Promise( function (resolve, reject) {
Users.findOne({ username : id }).then( function(user){
//If you use lodash you can do _.isNull(user)
if(user == null){
return reject({error : 'User not found'});
}
user.exec(function(userdata, error) {
if(userdata){
return resolve(userdata);
}
if(error){
return reject({error : 'Error while executing query'});
}
});
});
});
}
I don't really get why you are importing Users Model like that. I do not think Node will be able to fetch it like that.
And, you should require mongoose in your server.js
To catch the rejection you need the following code:
UserFactory.userNameToId(id).then( function(response){
if(response.error){
console.log('error '+response.error);
}
if(response){
console.log('Got response '+response);
}
});