I am updating and returning(new Object) a existing object in the database with mongoose findOneAndUpdate but getting an error
Error
response is not defined
at Function.module.exports.updateProfile ........
In router File
router.post('/edit_profile', (req, res) => {
let updateProfile = new Profile({
name: req.body.name,
email: req.body.email,
username: req.body.username,
gender: req.body.gender,
bio: req.body.bio,
user_id: req.body.user_id
});
console.log(updateProfile); //consoling data Place(1)
Profile.updateProfile(updateProfile.user_id, (err, user) => {
if (err) throw err;
else {
console.log("Update User");
console.log(user);
res.json({
user: user
})
}
})
})
consoled data at Place(1)
{ _id: 5c9cd517b3b7db248c6d7981,
name: 'Shivva',
email: 'ritinbhardwaj933#gmail.com',
username: 'zzz',
gender: 'Male',
bio: 'I am HOwdy Member',
user_id: '5c9cd47bf3d9bb1ea8cbfcbe' }
In profile.js
module.exports.updateProfile = (id, callback) => {
let query = { user_id: id };
console.log(query); //consoling data Place(2)
Profile.findOneAndUpdate(query, { $set: response }, { new: true }, (err, user) => {
if (err) throw err;
else {
callback(null, user);
}
});
}
consoled data at Place(2)
{ user_id: '5c9cd47bf3d9bb1ea8cbfcbe' }
Error
The error i am getting is response is not defined a the Function.module.exports.updateProfile
Error
the accepted solution worked but now it is returning the error
collection.findAndModify is deprecated. Use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
If you look closely, in this line you have used variable response but never have you initialised it.
Profile.findOneAndUpdate(query, { $set: response }, { new: true }, (err, user) => {
That response word should be replaced with an object with whatever changes you want eg.{ name: 'jason bourne' }
And honestly you don't need to create an instance like what you have done below because you aren't using that anywhere.
let updateProfile = new Profile({
name: req.body.name,
email: req.body.email,
username: req.body.username,
gender: req.body.gender,
bio: req.body.bio,
user_id: req.body.user_id
});
Related
I am newbie and working for my thesis.
I was able to create insert and delete function but getting issues updating the data.
The below is the code under the controllers folder:
Insert Document:
module.exports.register = (params) => {
let user = new User({
firstName: params.firstName,
lastName: params.lastName,
department: params.department,
position: params.position,
email: params.email,
mobileNo: params.mobileNo,
password: bcrypt.hashSync(params.password, 10),
isAdmin: params.isAdmin,
departments: {
departmentId: params.departmentId
}
})
return user.save().then((user, err) => {
return (err) ? false : true
})
}
Delete Document:
module.exports.deleteUser = (params) => {
return User.findByIdAndRemove(params.userId).then((user, err) => {
return (err) ? false : true
})
}
While the below is the code for the routers:
Insert Document:
router.post('/register', (req, res) => {
UserController.register(req.body).then(result => res.send(result))
});
Delete Document:
router.delete('/delete/:id', (req, res) => {
let userId = req.params.id
UserController.deleteUser({userId}).then(user => res.send(user))
});
What I've tried to far is to use the delete logic but instead of findOneAndRemove, I used findOneAndUpdate but it's not updating the data. It just sending true value but not updating the document.
I've also tried some of the logic in YouTube and some here but it doesn't matched the way we construct the data so I'm having difficulties understanding them.
The target is to update the same values in the register using the id of the user.
I'm trying to update using this code:
Controllers:
module.exports.updateUser = (params) => {
return User.findOneAndUpdate(params.userId, (user, err) => {
return (err) ? false : true
})
}
Routes:
router.post('/update/:id', (req, res) => {
UserController.updateUser(req.params.id).then(user => res.send(user))
});
I've also tried to add the parameters but it's not working. What I want to update is the whole details example:
firstName: params.firstName,
lastName: params.lastName,
department: params.department,
position: params.position,
email: params.email,
mobileNo: params.mobileNo,
password: bcrypt.hashSync(params.password, 10),
isAdmin: params.isAdmin,
departments: {
departmentId: params.departmentId
}
Sample User:
{
"userId": "60f649bd8896c80004b3ffbe",
"firstName": "Jane",
"lastName": "Joe",
"department": "Accounting",
"position": "head",
"email": "janedoe#mail.com",
"mobileNo": "0",
"password": "pass123",
"isAdmin": "yes",
"departments": {
"departmentId": "60efcbec769cf60004b85319"
}
}
Here's my update code:
Controller:
module.exports.updateUserData = (params) => {
const dataToUpdate = {
firstName: params.firstName,
lastName: params.lastName,
department: params.department,
position: params.position,
email: params.email,
mobileNo: params.mobileNo,
password: bcrypt.hash(params.password, 10),
isAdmin: params.isAdmin,
departments: {
departmentId: params.departmentId
}
}
User.findOneAndUpdate({userId:params.userId}, {$set:dataToUpdate}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
});
}
Routers:
router.post('/update-user/:id', (req, res) => {
let userId = req.params.id;
UserController.updateUserData({userId}).then(doc => res.send(doc))
})
Using this code I am getting error message: TypeError: Cannot read property 'then' of undefined under routers folder.
You should try following. It might meet your requirement
const dataToUpdate = {
firstName: params.firstName,
lastName: params.lastName,
department: params.department,
position: params.position,
email: params.email,
mobileNo: params.mobileNo,
password: bcrypt.hashSync(params.password, 10),
isAdmin: params.isAdmin,
departments: {
departmentId: params.departmentId
}
}
User.findOneAndUpdate({userId:params.userId}, {$set:dataToUpdate}, {new: true}, (err, doc) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
});
I'm working on adding a last login functionality to my Node app and can't seem to get it to work. Here's what I've got for a mongoose user schema:
userSchema = new mongoose.Schema({
username: {
type: String,
unique: true
},
password: String,
email: {
type: String,
unique: true
},
avatar: String,
firstName: String,
lastName: String,
lastLogin: {
type: Date,
default: Date.now
},
resetPasswordToken: String,
resetPasswordExpires: Date,
isAdmin: {
type: Boolean,
default: false
}
});
userSchema.plugin(passportLocalMongoose);
userSchema.statics.newLogin = function login(id, callback) {
return this.findByIdAndUpdate(id,{'$set' : { 'lastLogin' : Date.now()} }, { new : true }, callback);
};
module.exports = mongoose.model("User", userSchema);
Here's my login route:
router.post("/login", passport.authenticate("local",
{
failureRedirect: "/login"
}), function(req, res) {
User.findOneAndUpdate(req.username, {lastLogin: Date.now()}, (err, data) => {
if(err) console.log(err);
else console.log("Successfully updated the lastLogin", data);
res.redirect("/players");
});
});
I've been able to get the initial date to stick when the account is created; however, when I login with that same account the date remains unchanged. What am I missing here?
There are a few other questions with similar topics, but none seem to resolve my issue. Specifically, this question where I've implemented part of the solution to no avail. Thanks in advance for the help!
Here's the code currently being tested, example req.body:
{ username: 'anyUserHere', password: 'anyPasswordHere' }
req.user:
{
isAdmin: true,
_id: 5e9b301a6bb78973c9ec8fae,
username: 'anyUserHere',
salt: 'saltValue',
hash: 'hashValue',
__v: 0,
avatar: '../images/admin.jpg',
email: 'example#example.com',
firstName: 'first',
lastName: 'last',
password: 'anyPasswordHere',
lastLogin: 2020-05-22T18:35:50.941Z
}
So in this case, the 'anyUserHere' example should be the one being updated, but the update occurs to the first user in Mongo. Console output:
Successfully updated the lastLogin {
isAdmin: false,
_id: 5e939f988ced3e0428c8b521,
username: 'test',
__v: 0,
lastLogin: 2020-05-22T18:38:59.836Z
}
Can you update the User.newLogin(); with the below code and try
User.newLogin(id, (err, data) => {
if(err) console.log(err);
else console.log("Successfully updated the lastLogin", data);
});
router.post("/login", passport.authenticate("local",
{
failureRedirect: "/login"
}), function(req, res) {
User.newLogin(id, (err, data) => {
if(err) console.log(err);
else console.log("Successfully updated the lastLogin", data);
res.redirect("/players");
});
});
Edit
According to the current approach with findOneAndUpdate you need to make the following updated to the filter
User.findOneAndUpdate({username: req.username}, {lastLogin: Date.now()}, (err, data) => {
if(err) console.log(err);
else console.log("Successfully updated the lastLogin", data);
res.redirect("/players");
});
I am struggling to update some specific arrays in my UserSchema with the mongoose function findByIdAndUpdate().
This is my UserSchema:
const UserSchema = new mongoose.Schema({
mail: {type: String, required: true, unique: true},
password: {type: String, required: true},
friends: [{id: String}],
prot: [{
id: String,
admin: Boolean,
}]
});
I only want to update the prot element, this is how I want todo this:
User.findByIdAndUpdate(req.body.userId, {
$set: { prot: [{ id: req.body.lockId, admin: req.body.isAdmin }] }, function(err, user) {
if (err) {
return res.status(500).send({
message: err.message || "Some error occured while updating user"
});
}
if (!user) {
return res.status(404).send({
message: "User not found"
});
}
return res.status(200).send(user);
}
})
But when I try to send a request via Postman, I didn't get an response or error..
FindByIdAndUpdate doesn't return updated document per default, you should add option {new:true}. You have mixed brackets too. Do it like below:
User.findByIdAndUpdate(
req.body.userId,
{
$set: {
prot: [{
id: req.body.lockId,
admin: req.body.isAdmin
}]
}
},
{ new: true },
function(err, user) {
if (err) {
return res.status(500).send({
message: err.message || "Some error occured while updating user"
});
}
if (!user) {
return res.status(404).send({
message: "User not found"
});
}
return res.status(200).send(user);
}
);
If you want to update a specific record inside an array of objects. You can do it like this.
User.update(
{ _id: req.body.userId,
prot:
{ $elemMatch: { id: req.body.lockId }}
},
{ $set:
{ prot: { admin: req.body.isAdmin }
}
},(error,result)=>{
if(error){
//handle error
}
console.log(result);
}
)
am using mongoose for my schema design i want to check a user collection if a device id exist in am array if false push the device into the user devices array
here is ma user schema
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var deviceSchema = mongoose.Schema(
{
macAddress: {type: String, required: true, unique: true},
createdAt: {type: Date, default: Date.now},
}
)
var Device = mongoose.model('Device', deviceSchema);
module.exports = Device;
here is my user schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = Schema(
{
firstname: {type: String, required: true},
lastname: {type: String, required: true},
email: {type: String, required: true, unique: true},
username: {type: String, required: true, unique: true},
password: {type: String, required: true},
createdAt: {type: Date, default: Date.now},
devices: [{ type: Schema.Types.ObjectId, ref: 'Device1' }]
}
)
var User = mongoose.model('User', userSchema);
module.exports = User;
and here is my nodejs router
router.post('/user/device/:username', function(req, res, next) {
if(!req.body.macAddress) {
sendJSONresponse(res, 400, {
"message": "Device Mac-Address required"
});
return;
}
User.findOne({ username: req.params.username }, function(err, user) {
if (err) { return next(err); }
if (!user) { return sendJSONresponse(res, 400, {
"message": "user not found"
});
}
Device.findOne({macAddress : req.body.macAddress}, function(err, device){
if(err){return next(err);}
if(!device){
sendJSONresponse(res, 400, {
"message": "No device with that macaddress"
});
return;
}
User.find({ devices: { $elemMatch: { $eq: req.body.macAddress} } }, function(err, users){
if(err){return next(err);}
if(users){
sendJSONresponse(res, 400, {
"message": "Device already assigned to a user"
});
return;
}else{
user.devices.push(device._id);
user.save(function(err) {
if(err){return next(err);}
sendJSONresponse(res, 200, user);
});
}
});
});
});
});
after doing all this when i try using the api with postman is tells me The server couldn't send a response: please help me fix my code
You are pushing device Id to devices array
user.devices.push(device._id)
but you are trying to elemMatch macAddress
User.find({ devices: { $elemMatch: { $eq: req.body.macAddress} } }..
When it should be
User.find({ devices: { $elemMatch: { $eq: device._id} } }..
Your have to change elemMatch param to device._id to make it correct.
router.post('/user/device/:username', function(req, res, next) {
if(!req.body.macAddress) {
sendJSONresponse(res, 400, {
"message": "Device Mac-Address required"
});
return;
}
User.findOne({ username: req.params.username }, function(err, user) {
if (err) { return next(err); }
if (!user) { return sendJSONresponse(res, 400, {
"message": "user not found"
});
}
Device.findOne({macAddress : req.body.macAddress}, function(err, device){
if(err){return next(err);}
if(!device){
sendJSONresponse(res, 400, {
"message": "No device with that macaddress"
});
return;
}
User.find({ devices: { $elemMatch: { $eq: device._id} } }, function(err, users){
if(err){return next(err);}
if(users){
sendJSONresponse(res, 400, {
"message": "Device already assigned to a user"
});
return;
}else{
user.devices.push(device._id);
user.save(function(err) {
if(err){return next(err);}
sendJSONresponse(res, 200, user);
});
}
});
});
});
});
Use debugger to go through code step by step, and see what's going on. If you don't know how to debug, take a look at https://code.visualstudio.com/docs/editor/debugging. It is a free tool.
im using sequelize, node js and type script. i need to convert following command to type script.
return sequelize.transaction().then(function (t) {
return User.create({
firstName: 'Homer',
lastName: 'Simpson'
}, {transaction: t}).then(function (user) {
return user.addSibling({
firstName: 'Lisa',
lastName: 'Simpson'
}, {transaction: t});
}).then(function () {
return t.commit();
}).catch(function (err) {
return t.rollback();
});
});
Can any one help me to solve this or give some examples regarding sequlize transaction in type script
thank you in advances
Example
return sequelize.transaction((t:Sequelize.Transaction) => {
return User.create({
firstName: 'Homer',
lastName: 'Simpson'
}, {transaction: t})
.then((user) => {
return user.addSibling({
firstName: 'Lisa',
lastName: 'Simpson'
}, {transaction: t});
})
});
});
Ref http://ngerakines.me/2016/04/11/sequelize/