Mongoose pre updateOne hook is not invoked while doc is updated - mongodb

I have this schema and fields like basicSalary can be edited by admin through dashboard UI, the pre save hook works fine to calculate fields, followed by pre updateOne hook to update the doc when it's edited by admin
const salariesSchema = mongoose.Schema({
employeeId: {
type: mongoose.Schema.Types.ObjectId,
ref: "employee",
required: true,
},
month: { type: String, required: true },
year: { type: String, required: true },
basicSalary: { type: Number, default: 0, required: true },
accomodation: { type: Number, default: 0 },
transportation: { type: Number, default: 0 },
bonus: { type: Number, default: 0 },
SSC: { type: Number, default: 0 },
incomeTax: { type: Number, default: 0 },
medicalInsurance: { type: Number, default: 0 },
loan: { type: Number, default: 0, default: null },
totalEarnings: { type: Number },
totalDeductions: { type: Number },
netSalary: { type: Number },
});
salariesSchema.pre("save", function (next) {
this.SSC = this.basicSalary * 0.07;
this.totalEarnings =
this.basicSalary + this.accomodation + this.transportation + this.bonus;
this.totalDeductions =
this.incomeTax + this.medicalInsurance + this.loan + this.SSC;
this.netSalary = this.totalEarnings - this.totalDeductions;
next();
});
salariesSchema.pre("updateOne", function (next) {
this.SSC = this.basicSalary * 0.07;
this.totalEarnings =
this.basicSalary + this.accomodation + this.transportation + this.bonus;
this.totalDeductions =
this.incomeTax + this.medicalInsurance + this.loan + this.SSC;
this.netSalary = this.totalEarnings - this.totalDeductions;
next();
});
routes > salary..js
const Salary = require("../models/Salary");
const editSalary = async (req, res) => {
try {
const salary = Salary.findById(req.body._id);
await salary.updateOne({ $set: req.body });
res.status(200).json("salary has been updated successfully");
} catch (err) {
console.log(err);
res.status(400).json(err);
}
};
if admin for example increased basicSalary by 50, totalEarningsand netSalary values should also be updated by 50 based on the calculations in pre updateOne hook, but that doesn't work, what's wrong here ?

You should create separate pre hook for other types of queries. For example, you can add updateOne pre hook:
salariesSchema.pre("save", function (next) {
this.SSC = this.basicSalary * 0.07;
this.totalEarnings =
this.basicSalary + this.accomodation + this.transportation + this.bonus;
this.totalDeductions =
this.incomeTax + this.medicalInsurance + this.loan + this.SSC;
this.netSalary = this.totalEarnings - this.totalDeductions;
next();
});
salariesSchema.pre('updateOne', function() {
this.SSC = this.basicSalary * 0.07;
this.totalEarnings =
this.basicSalary + this.accomodation + this.transportation + this.bonus;
this.totalDeductions =
this.incomeTax + this.medicalInsurance + this.loan + this.SSC;
this.netSalary = this.totalEarnings - this.totalDeductions;
next();
});

it turned out that i can't access fields directly by using this.fieldName, i solved it by using this.get("fieldName") converted into a number, and using this.set ( see documentation ) instead of return fieldName = expression
let me know if you have a better way to do it
salariesSchema.pre("updateOne", function (next) {
this.set({ SSC: Number(this.get("basicSalary")) * 0.07 });
this.set({
totalDeductions:
Number(this.get("incomeTax")) +
Number(this.get("medicalInsurance")) +
Number(this.get("loan")) +
Number(this.get("SSC")),
});
this.set({
totalEarnings:
Number(this.get("basicSalary")) +
Number(this.get("accomodation")) +
Number(this.get("transportation")) +
Number(this.get("bonus")),
});
this.set({
netSalary:
Number(this.get("totalEarnings")) - Number(this.get("totalDeductions")),
});
next();
});

Related

Mongoose .insertMany only saving object id and and version

while using mongoose insertMany to populate a collection I noticed it's only saving the object id and version for each data in the array as such
but my model and data are structured as shown in code below
//SCHEMA MODEL
const { Schema, model } = require("mongoose");
const staffSchema = new Schema({
Phone: { String },
Timestamp: { String },
Fullname: { String },
});
module.exports = { staffConvert: model("staff", staffSchema) };
though my actual data is coming from converting excel to json but this a sample of the data
//SAMPLE DATA ARRAY
const data = [
{
Phone: "92893249",
Timestamp: "8/24/2020 10:08:25",
Fullname: "Musa Yahaya",
},
{
Phone: "92893249",
Timestamp: "8/24/2020 10:08:25",
Fullname: "Musa Yahaya",
},
];
try {
if (data.length === 0) return console.log("No data to upload");
await staffConvert
.insertMany(data)
.then((docs) => {
console.log(
"success_msg",
"Staffs record uploaded successfully" + " " + docs
);
// req.flash("success_msg", "Staffs record uploaded successfully");
})
.catch((error) => {
console.log(
"Staffs record uploaded failed" + " " + error.message
);
});
} catch (error) {
console.log("Staffs record uploaded failed" + " " + error.message);
// req.flash(
// "error_msg",
// "Staffs record uploaded failed" + " " + error.message
// );
}
You have to make change to your model. You're defining your attribute as object type. If you want to define it like that, you have to explicitly tell mongo that it's string type not object.
const staffSchema = new Schema({
Phone: String,
Timestamp: { type: String },
});
This should solve your issue

This.localStream is null

I'm trying to develop and application that allow to a medic and a patient be able to communicate using an Api called connectycube, the chat and video call work, the problem is with to mute sound and video. I have implemented the buttons to mute sound and video, all this using jQuery dialogs, the first time I mute audio or video works, but when I close the dialog finishing the session and then I open the dialog with a new session, to mute audio and video do not work anymore and the message in the console is This.localStream is null
My Source Code:
const CREDENTIALS = {
appId: 'xxxxx',
authKey: 'xxxxx',
authSecret: 'xxxxx'
};
ConnectyCube.init(CREDENTIALS);
//This is a button in a main jquery dialog, this is the beginning of all
{
text: 'VideoCall',
click: function () {
$('#dv_progess').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.createSession().then((session) => {
$('#dv_progess').dialog('close');
signup_user();
$('#dv_videocall').dialog('option', 'position', {my: 'right top', at: 'right top', of: window}).dialog('open');
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progess').dialog('close');
$('#dv_message').html('Error=>' + JSON.stringify(error)).dialog('open');
});
}
},
function signup_user() {
var login = 'P' + $('#hd_idusr').val();
/*Buscar si existe usuario registrado en la API*/
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.users.get({login: login}).then((result) => {
console.log('User Exists:' + result.user.id);
$('#dv_progress').dialog('close');
chat();
}).catch((error) => {
$('#dv_progress').dialog('close');
console.log('User not exists [' + error.info.message + ']');
var password = $('#txt_birthdate').val().replace(/-/g, '') + '*';
var email = $('#hd_email').val();
email = email ? email : login + '#email.com';
const userProfile = {
login: login,
password: password,
full_name: $('#txt_names').val(),
email: email
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.users.signup(userProfile).then((data) => {
console.log('ok=>' + data.user.id);
$('#dv_progress').dialog('close');
chat();
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
});
}
function chat() {
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
var login_patient = 'P' + $('#hd_idusr').val();
ConnectyCube.users.get({login: login_patient}).then((result) => {
$('#dv_progress').dialog('close');
var id_patient = result.user.id;
$('#hd_idpatient').val(id_patient);
const userCredentials = {
login: 'S' + $('#txt_medic').attr('data-id-user'),
password: $('#txt_medic').attr('data-psw')
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.createSession(userCredentials).then((session) => {
$('#dv_progress').dialog('close');
console.log(JSON.stringify(session));
console.log('Medic Created session');
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.login(userCredentials).then((user) => {
var id_professional = user.id;
console.log('Medic login succesful=>' + id_professional);
$('#hd_idprofessional').val(id_professional);
const chatCredentials = {
userId: id_professional,
password: $('#txt_medic').attr('data-psw')
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.chat.connect(chatCredentials).then(() => {
$('#dv_progress').dialog('close');
console.log('Medic Connected to chat');
console.log('Id Paciente:' + id_patient);
const dialogParams = {
type: 3,
occupants_ids: [id_patient]
};
$('#dv_progress').html('<div class="dv_progress">Connecting</div>').dialog('open');
ConnectyCube.chat.dialog.create(dialogParams).then(dialog => {
$('#dv_progress').dialog('close');
console.log(JSON.stringify(dialog));
console.log('Dialog Created:' + dialog._id);
$('#hd_iddialog').val(dialog._id);
$('#dv_messagearea').prop('contenteditable', true);
$('#btn_sendmsg,#btn_startvideocall,#btn_finishvideocall').prop('disabled', false);
}).catch(error => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
}).catch((error) => {
console.log('Error:' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error:' + JSON.stringify(error)).dialog('open');
});
}).catch((error) => {
console.log('Error:' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error:' + JSON.stringify(error)).dialog('open');
});
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
/*Fin Login Medico*/
}).catch((error) => {
console.log('Error=>' + JSON.stringify(error));
$('#dv_progress').dialog('close');
$('#dv_messages').html('Error=>' + JSON.stringify(error)).dialog('open');
});
}
function onMessage(userId, message) {
console.log('[ConnectyCube.chat.onMessageListener] callback:', userId, message);
var dv_message = $('#dv_messageschat');
dv_message.append('<div><b>Patient:</b>' + message.body + '</div>');
dv_message.scrollTop(dv_message[0].scrollHeight);
}
function isTyPing(isTyping, userId, dialogId) {
console.log("[ConnectyCube.chat.onMessageTypingListener] callback:", isTyping, userId, dialogId);
}
function sendMessage() {
ConnectyCube.chat.sendIsStopTypingStatus($('#hd_idpatient').val());
var mensaje = $('#dv_messagearea').text();
const message = {
type: 'chat',
body: mensaje,
extension: {
save_to_history: 1,
dialog_id: $('#hd_iddialog').val()
},
markable: 1
};
message.id = ConnectyCube.chat.send($('#hd_idpatient').val(), message);
var dv_message = $('#dv_messageschat');
dv_message.append('<div><b>Yo:</b>' + mensaje + '</div>');
dv_message.scrollTop(dv_message[0].scrollHeight);
$('#dv_messagearea').html('');
}
$('#dv_messagearea').keypress(function (e) {
ConnectyCube.chat.sendIsTypingStatus($('#hd_idpatient').val());
setTimeout(function () {
ConnectyCube.chat.sendIsStopTypingStatus($('#hd_idpatient').val());
}, 1000);
if (e.keyCode == 13) {
sendMessage();
return false;
}
});
function startVideo() {
const calleesIds = [$('#hd_idprofessional').val(), $('#hd_idpatient').val()]; /*User's ids*/
const sessionType = ConnectyCube.videochat.CallType.VIDEO;
const additionalOptions = {};
const session = ConnectyCube.videochat.createNewSession(calleesIds, sessionType, additionalOptions);
const mediaParams = {
audio: true,
video: true,
options: {
muted: true,
mirror: true
}
};
session.getUserMedia(mediaParams).then((localStream) => {
console.log(JSON.stringify(localStream));
session.attachMediaStream('vd_video1', localStream);
/*Iniciar la llamada*/
const extension = {};
session.call(extension, (error) => {
console.log(JSON.stringify(error));
});
$('#btn_finishvideocall').on('click', {x: session}, finishCall);
}).catch((error) => {
console.log(JSON.stringify(error));
});
}
function finishCall(e) {
const extension = {};
e.data.x.stop(extension);
/*Clean local stream*/
var videoElem1 = document.getElementById('vd_video1'),
stream1 = videoElem1.srcObject;
if (stream1 != null) {
var tracks = stream1.getTracks();
tracks.forEach(function (track) {
track.stop();
});
videoElem1.srcObject = null;
}
/*Clean remote stream*/
var videoElem2 = document.getElementById('vd_video2'),
stream2 = videoElem2.srcObject;
if (stream2 != null) {
var tracks = stream2.getTracks();
tracks.forEach(function (track) {
track.stop();
});
videoElem2.srcObject = null;
}
}
$('#dv_controllsvideocall').find('button').prop('disabled', true);
$('#btn_mutesound,#btn_mutevideo').hide();
function setSound(e) {
const session = e.data.x;
if (e.data.y == 'mute') {
$('#btn_mutesound').show();
$('#btn_unmutesound').hide();
session.mute('audio');
console.log('muted audio');
} else {
$('#btn_mutesound').hide();
$('#btn_unmutesound').show();
session.unmute('audio');
console.log('unmuted audio');
}
}
function setVideo(e) {
const session = e.data.x;
if (e.data.y == 'mute') {
$('#btn_mutevideo').show();
$('#btn_unmutevideo').hide();
session.mute('video');
console.log('muted video');
} else {
$('#btn_mutevideo').hide();
$('#btn_unmutevideo').show();
session.unmute('video');
console.log('unmuted video');
}
}
function acceptedCall(session, userId, extension) {
console.log('Accepted call');
$('#dv_controllsvideocall').find('button').prop('disabled', false);
}
function setStream(session, userID, remoteStream) {
console.log('stream assigned');
session.attachMediaStream('vd_video2', remoteStream);
$('#btn_mutesound').on('click', {x: session, y: 'unmute'}, setSound);
$('#btn_unmutesound').on('click', {x: session, y: 'mute'}, setSound);
$('#btn_mutevideo').on('click', {x: session, y: 'unmute'}, setVideo);
$('#btn_unmutevideo').on('click', {x: session, y: 'mute'}, setVideo);
}
function onStopCall(session, userId, extension) {
console.log('Finished Call');
}
ConnectyCube.chat.onMessageListener = onMessage;
ConnectyCube.chat.onMessageTypingListener = isTyPing;
ConnectyCube.videochat.onAcceptCallListener = acceptedCall;
ConnectyCube.videochat.onRemoteStreamListener = setStream;
ConnectyCube.videochat.onStopCallListener = onStopCall;
$('#btn_sendmsg').click(function () {
sendMessage();
});
$('#btn_startvideocall').click(function () {
startVideo();
});
$('#btn_exitvideocall').click(function () {
$('#dv_videocall').dialog('close');
});
/*Dialog for video call*/
$('#dv_videocall').dialog({
autoOpen: false,
resizable: false,
height: 600,
width: 220,
modal: false,
close: function () {
$(this).find('input').val('');
$('#dv_messagearea').prop('contenteditable', false).html('');
$('#dv_messageschat').html('');
$('#btn_sendmsg,#btn_startvideocall,#btn_finishvideocall').prop('disabled', true);
$('#dv_controllsvideocall').find('button').prop('disabled', true);
if (ConnectyCube.chat.isConnected) {
$('#btn_finishvideocall').trigger('click');
ConnectyCube.chat.disconnect();
ConnectyCube.logout().catch((error) => {
console.log('logout=>' + JSON.stringify(error));
});
ConnectyCube.destroySession().catch((error) => {
console.log('destroySession=>' + JSON.stringify(error));
});
}
}
});
$(window).bind('beforeunload', function () {
if (ConnectyCube.chat.isConnected) {
$('#btn_finishvideocall').trigger('click');
ConnectyCube.chat.disconnect();
ConnectyCube.logout().catch((error) => {
console.log('logout=>' + JSON.stringify(error));
});
ConnectyCube.destroySession().catch((error) => {
console.log('destroySession=>' + JSON.stringify(error));
});
}
});
I think the problem is in the function finishCall() when I clean the video tag and I don't know if that is the right way to free the resources. Despite this the chat and video call still work.
If someone has experience please help me, becasue I didn't found any solution, thanks in advance.

How can i add 3 fields with the Mongoose Model using pre function

I am bout to add the prelimGrade, midtermGrade, finalsGrade on my overall grade and divide it to 3. This code is giving me null value.
i have tried searching here and found a problem with the solution but the value is also giving me null.
Here is my code on my Test.js schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const TestSchema = new Schema({
prelim: { type: Number, default: 1 },
midterm: { type: Number, default: 1 },
finals: { type: Number, default: 1 },
overall: { type: Number }
});
module.exports = Test = mongoose.model("tests", TestSchema);
TestSchema.pre("save", function(next) {
this.overall = (this.prelim + this.midterm + this.finals)/3;
next();
});
and this is my code on my route
router.post("/test", (req, res) => {
const { prelim, midterm, finals, overall } = req.body;
const test = new Test({
prelim,
midterm,
finals,
overall
});
test.save().then(test => {
res.json(test);
});
});
i expect that it gives me value but it gives me null.
The module.exports should be after the testSchema. This worked for me

How to close a active MongoDB connection with mongoose after job is done?

As you can see, I am connecting to the database, reading multiple JSON files from a directory and import them into the MongoDB server with help of mongoose.
After this job is done, I would like to close the connection and print out "job is done"
How do I do that?
var mongoose = require('mongoose'),
_ = require('lodash'),
fs = require('fs'),
path = require('path');
mongoose.Promise = require('bluebird'),
mongoose.connect('mongodb://localhost/eclass');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
// create db schema
var EclassSchema = new mongoose.Schema({
xsi: {
xsitype: 'string',
id: 'string'
},
date_of_original_definition: 'string',
date_of_current_version: 'string',
date_of_current_revision: 'string',
revision: 'string',
status: 'string',
source_language: {
country_code: 'string',
language_code: 'string'
},
preferred_name: 'string',
definition: 'string',
its_superclass: 'string',
hierarchical_position: 'string',
//keywords: 'string'
});
// Create model
var Eclass = mongoose.model('Eclass', EclassSchema);
const pjsons = path.join(__dirname, '/../', 'file-operations', 'json-files');
console.log(pjsons);
function readFiles(pjsons, onError) {
fs.readdir(pjsons, function(err, filenames) {
if(err) {
onError(err);
return;
}
filenames.forEach(function(filename) {
fs.readFile(pjsons + '/' + filename, 'utf-8', function(err, data) {
if(err) {
onError(err);
return;
}
data = JSON.parse(data);
// Digging down into the json code
const ontomlOntoml = data['dic:eclass_dictionary']['ontoml:ontoml'];
const onto = _.first(ontomlOntoml);
const dictionary = onto['dictionary'];
const contClasses = _.first(dictionary);
const containedClasses = contClasses['contained_classes'];
const ontClass = _.first(containedClasses);
const ontomlClass = _.find(ontClass);
//Arrays
const xsiArray = _.map(ontomlClass, '$');
const date_of_original_definitionArray = _.map(ontomlClass, 'date_of_original_definition');
const date_of_current_versionArray = _.map(ontomlClass, 'date_of_current_version');
const date_of_current_revisionArray = _.map(ontomlClass, 'date_of_current_revision');
const revisionArray = _.map(ontomlClass, 'revision');
const statusArray = _.map(ontomlClass, 'status');
const sourceLanguageArray = _.map(ontomlClass, 'source_language');
const preferredNameArray = _.map(ontomlClass, 'preferred_name');
const definitionArray = _.map(ontomlClass, 'definition');
const itsSuperclassArray = _.map(ontomlClass, 'its_superclass');
const hierarchical_positionArray = _.map(ontomlClass, 'hierarchical_position');
//const keywordsArray = _.map(ontomlClass, 'keywords');
// Looping and storing the data into mongodb
//for (var i = 0; i < hierarchical_positionArray.length; i++) {
for (var i = 0; i < 2; i++) {
//console.log(hierarchical_positionArray[i]);
var newEclass = new Eclass();
newEclass.xsi.xsitype = xsiArray[i]['xsi:type'];
newEclass.xsi.id = xsiArray[i]['id'];
newEclass.date_of_original_definition = date_of_original_definitionArray[i];
newEclass.date_of_current_version = date_of_current_versionArray[i];
newEclass.date_of_current_revision = date_of_current_revisionArray[i];
newEclass.revision = revisionArray[i];
newEclass.status = statusArray[i];
newEclass.source_language.country_code = sourceLanguageArray[i][0].$.country_code;
newEclass.source_language.language_code = sourceLanguageArray[i][0].$.language_code;
newEclass.preferred_name = preferredNameArray[i][0].label[0]._;
newEclass.definition = definitionArray[i][0].text[0]._;
newEclass.its_superclass = itsSuperclassArray[i][0].$.class_ref;
newEclass.hierarchical_position = hierarchical_positionArray[i];
//newEclass.keywords = keywordsArray[i][0].label[0]._;
newEclass.save(function (err) {});
}
});
});
});
}
readFiles(pjsons);
});
mongoose.disconnect() closes all opened connections. for more
http://mongoosejs.com/docs/api.html#index_Mongoose-disconnect
I solved it like this:
newEclass.save()
.then(function() {
mongoose.disconnect();
})
.catch(function(err) {
console.log('There was an error', err);
});
...
const mongoose = require('mongoose'),
parse = require('csv-parse'),
path = require('path'),
fs = require('fs');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/eclassCSV');
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
// create db schema
const EclassSchema = new mongoose.Schema({
codedName: { type: String, min: 10, max: 10 },
preferredName: { type: String, max: 80 },
definition: { type: String, max: 1023 },
level: { type: String, min: 1, max: 1 },
mkSubclass: { type: String, min: 1, max: 1 },
mkKeyword: { type: String, min: 1, max: 1 }
});
// Create MongoDB model with mongoose
const Eclass = mongoose.model('Eclass', EclassSchema);
const p = path.join(__dirname, '/../', 'file-operations', 'csv-files');
//console.log(p);
const parser = parse({delimiter: ';'}, function(err, data){
//console.log(data);
//const supplier = data[0][0];
const codedName = data.map((item,i) => data[i][6]);
const preferredName = data.map((item,i) => data[i][7]);
const definition = data.map((item,i) => data[i][8]);
const level = data.map((item,i) => data[i][13]);
const mkSubclass = data.map((item,i) => data[i][14]);
const mkKeyword = data.map((item,i) => data[i][15]);
// Looping and storing the data into mongodb
//console.log(ontomlClass.length);
for (let i = 0; i < data.length; i++) {
//console.log(hierarchical_positionArray[i]);
const newEclass = new Eclass();
newEclass.codedName = codedName[i];
newEclass.preferredName = preferredName[i];
newEclass.definition = definition[i];
newEclass.level = level[i];
newEclass.mkSubclass = mkSubclass[i];
newEclass.mkKeyword = mkKeyword[i];
newEclass.save()
.then(function() {
mongoose.disconnect();
})
.catch(function(err) {
console.log('There was an error', err);
});
}
});
fs.createReadStream(p + '/One-eClass-10_0_CC_en.csv').pipe(parser);
});

mongoose updating a field in a MongoDB not working

I have this code
var UserSchema = new Schema({
Username: {type: String, index: true},
Password: String,
Email: String,
Points: {type: Number, default: 0}
});
[...]
var User = db.model('User');
/*
* Function to save the points in the user's account
*/
function savePoints(name, points){
if(name != "unregistered user"){
User.find({Username: name}, function(err, users){
var oldPoints = users[0].Points;
var newPoints = oldPoints + points;
User.update({name: name}, { $inc: {Points: newPoints}}, function(err){
if(err){
console.log("some error happened when update");
}
else{
console.log("update successfull! with name = " + name);
User.find({Username: name}, function(err, users) {
console.log("updated : " + users[0].Points);
});
}
});
});
}
}
savePoints("Masiar", 666);
I would like to update my user (by finding it with its name) by
updating his/her points. I'm sure oldPoints and points contain a
value, but still my user keep being at zero points. The console prints
"update successful".
What am I doing wrong? Sorry for the stupid / noob question.
Masiar
It seems you are doing a few unstandard things:
Use findOne instead of find if you want to load just one user
Calling Model.update should be done to update records that you have not loaded
$inc is adding oldPoints, so the new value will be 2*oldPoints + newPoints
You are using name as the conditional query instead of Username
I would rewrite the code into something like this:
User.findOne({Username: name}, function(err, user){
if (err) { return next(err); }
user.Points += points;
user.save(function(err) {
if (err) { return next(err); }
});
});
follow my code guy
User.update({ username: "faibaa" },
{ $inc: { point: 200000 } }, function(err,data){
return res.send(data);
});