Can't access a mongoose response object property - node.js

When I try to access an response obj from mongoose, it doesn't not return anything. Following is my code
//app.ts
import { User } from './Models/User';
router.get('/reset/:token', async (req, res) => {
const user = await User.findOne({ _id: '60a12460479e874db836d939' }).lean()
console.log(user)//returns an object with email property
console.log(user.email) //returns undefined
return res.json({
user,
})
})
Whereas this works fine
//app.ts
import { User } from '../Models/User';
router.get('/reset/:token', async (req, res) => {
const user = await User.findOne({ _id: '60a12460479e874db836d939' }, (err: any, user: any) => {
if (err) { console.log(err); }
console.log(user.email)//returns email
})
return res.json({
user,
})
})
I have tried researching about this problem. Most of them seem to point out schema. But my schema seems to be fine.
Following is my schema
//Models/User.ts
import mongoose from 'mongoose'
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true,
},
isAdmin: {
type: Boolean,
default: false
},
resetPasswordToken: String,
resetPasswordExpires: Date
})
export const User = mongoose.model('User', UserSchema);
Please advise.
Thank you.

Related

Log a user in and get their profile

I am attempting to log a user in to my DB. When I log the user in, it returns the first userId in the DB and not the user who logged in. I have been struggling with this for a while and really am at a dead end.
This is my POST route to log the user in:
// login
router.post("/login", async (req, res) => {
const user = await User.findOne({
email: req.body.email,
});
const secret = process.env.SECRET;
if (!user) {
return res.status(400).send("the user not found!");
}
if (user && bcrypt.compareSync(req.body.password, user.passwordHash)) {
const token = jwt.sign(
{
userId: user.id,
isAdmin: user.isAdmin,
},
secret,
{ expiresIn: "1d" }
);
res.status(200).send({ user: user.email, token: token });
} else {
res.status(400).send("password is wrong!");
}
});
The const user = await User.findOne({ email: req.body.email, }); this returns the wrong user.
When I query the endpoint get a users profile with the userId it gets the right information. So its got nothing to do with the DB.
This is the call in the app.
const handleSubmit = () => {
axios
.post(`${baseURL}users/login`, {
email: email,
passwordHash: password,
})
.then(res => {
console.log('USER ID TOKEN', res.data.token);
setbearerToken(res.data.token);
AsyncStorage.setItem('bearerToken', res.data.token);
const decoded = decode(res.data.token);
setTokenID(decoded.userId);
dispatch(setUser(res.data));
});
};
user.js model
const userSchema = mongoose.Schema({
contactName: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
phone: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
passwordHash: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
token: {
type: String,
},
isAdmin: {
type: Boolean,
default: false
},
clubName: {
type: String,
required: true,
},
clubAddress: {
type: String,
required: true,
},
clubEmail: {
type: String,
required: true,
},
clubPhone: {
type: String,
required: true,
},
clubWebsite: {
type: String,
required: true,
},
clubContact: {
type: String,
required: true,
},
})
Your schema doesn't have a field email to filter on.
const user = await User.findOne({
email: req.body.email,
});
Maybe you try clubEmail field. I reproduced the behavior and it looks like that mongoose ignores the filter if the field does not exist in the Schema an just returns the first document in the collection.
E.g.
const userSchema = new Schema(
{
name: String,
age: Number
}
)
const User = mongoose.model('User', userSchema);
User.findOne({name: "Superman"}, ...
Returns the user with name "Superman".
const userSchema = new Schema(
{
name: String,
age: Number
}
)
const User = mongoose.model('User', userSchema);
User.findOne({xname: "Superman"}, ...
But when using xname in the filter document which does not exist in my schema neither in the collection as field the query returns the first document in my test collection (its not Superman).
Also look here similar issue: Model.find Mongoose 6.012 always return all documents even though having filter
Issue reported: https://github.com/Automattic/mongoose/issues/10763
Migration Guide to Mongoose 6:
https://mongoosejs.com/docs/migrating_to_6.html#strictquery-is-removed-and-replaced-by-strict

Moongoose populate method returning an empty array

I am trying to fetch the blogs that a user has posted using mongoose populate method but not able to do so but when I try to look for the user who posted a blog I am able to do so. Tell me what I am doing wrong.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
blogPosts: [{ type: mongoose.Types.ObjectId, ref: "Blogs", required: true }],
});
const Users = mongoose.model("Users", userSchema);
module.exports = Users;
This is my user model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const blogSchema = new Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
image: {
type: String,
required: true,
},
user: {
type: mongoose.Types.ObjectId,
ref: "Users",
required: true,
},
});
const blogs = mongoose.model("Blogs", blogSchema);
module.exports = { blogs, blogSchema };
this is my blogs model
router.get("/users/:id", async (req, res) => {
let userBlogs;
try {
userBlogs = await users.find({ _id: req.params.id }).populate("blogPosts");
if (!userBlogs) {
return res.status(404).json({ msg: "No user found" });
}
return res.status(200).json(userBlogs);
} catch (err) {
return res.status(500).json({ err });
}
});
this is the route that I use for fetching all the blogs that a user has posted.This is just sending me back an empty posts array.
router.post("/newBlog/:id", async (req, res) => {
let blogAuthor;
try {
blogAuthor = await users.findOne({ _id: req.params.id });
} catch (err) {
return res.status(404).json({ message: "user not found" });
}
const newBlog = blogs({
title: req.body.title,
description: req.body.description,
image: req.body.imageUrl,
user: blogAuthor._id,
});
try {
await blogAuthor.blogPosts.push(newBlog);
await newBlog.save();
return res.status(200).json(blogAuthor.blogPosts);
} catch (err) {
return res.status(500).json(err);
}
});
the above is the route that I use to add new blog to the db.
router.get("/allBlogs", async (req, res) => {
let allBlogs;
try {
allBlogs = await blogs.find({}).populate("user");
} catch (err) {
return res.status(404).json(err);
}
res.status(200).json(allBlogs);
});
this is the route that sends all the blogs posted by all the users.
Interesting thing is that when I try to populate the user of a blogpost that is working exactly as expected it is populating the user of the blog from the users model however when I try to do the reverse that's not working. It is not populating all the blogs that a user has posted.

username on posts not updated after profile information update in Node.js/mongoosedb

I am using Mongoose with express.js and will like to update user information across all instances.
When user updates their profile information, it gets updated on their profile document in the mongoose database. However, their username has refused to be updated on their posts. I need their username updated across all instances including their post username. Thank you for the help
I know I am not doing something right.
Here are my codes:
//user updates profile information
router.put("/:id", async (req, res) =>{
if(req.body.userId === req.params.id){//we checked if the user id matched
if(req.body.password){
const salt = await bcrypt.genSalt(10);
req.body.password = await bcrypt.hash(req.body.password, salt);
}
try{
const updatedUser = await User.findByIdAndUpdate(req.params.id,{
$set: req.body,
}, {new: true}); //findbyidandupdate is an inbuilt method
res.status(200).json(updatedUser)
} catch(err){
res.status(500).json(err) //this handles the error if there is one from the server
}
} else{
res.status(401).json("You can only update your account!")
}
});
User updates post codes
router.put("/:id", async (req, res) =>{
//find post that will be updated
try{
const post = await Post.findById(req.params.id);
if(post.username == req.body.username )
try{
const updatedPost = await Post.findByIdAndUpdate(req.params.id,
$set: req.body
}, {new: true})//this makes it possible to see the updated post
res.status(200).json(updatedPost)
}catch(err){
res.status(401).json(err)
}
} else{
res.status(401).json("you can only update your posts")
}
}catch(err){
res.status(500).json(err)
}
});
User model
const UserSchema = new mongoose.Schema({
username:{
type: String,
required: true,
unique: true
},
email:{
type: String,
required: true,
unique: true
},
password:{
type: String,
required: true
},
profilePicture:{
type: String,
default: "",
},
}, {timestamps: true}
);
//exporting this schema
module.exports = mongoose.model("User", UserSchema); //the module name is "User"
Post model
const PostSchema = new mongoose.Schema(
{
title:{
type: String,
required: true,
unique: true
},
description:{
type: String,
required: true,
},
postPhoto:{
type: String,
required:false,
},
username:{
type: String,
required: true,
},
categories:{
type: Array,
required: false
},
}, {timestamps: true}
);
/ /exporting this schema
module.exports = mongoose.model("Post", PostSchema); //the module name is "Post"
where I used it in React.js for profile update
const handleUpdate = async (e) =>{
e.preventDefault();
dispatch({type: "UPDATE_START"})
const updatedUser = {
userId: user._id,
username,
email,
password
};
try{
const response = await axios.put("/users/" + user._id, updatedUser)
dispatch({type: "UPDATE_SUCCESS", payload: response.data})
setUpdated(true)
}catch(err){
}
}
Where I used it in React.js for post update
//this function handles the update of the post by the user
const handleUpdate = async () =>{
try{
await axios.put(`/posts/${post._id}`, {
username: user.username,
title:title,
description: description
});
// window.location.reload("/")
setUpdateMode(false)
}catch(err){
}
}

Saving an item that is specific to a user schema but not able to retrieve it back - mongoose

I have creared two schemas, user and medicine.
If a user adds medicines it should show up only in his/her account.
I am able to save the medicine ids to that specific user but i'm not able to get those medicines back i.e: medicines show for all the other users as well.
Here's the code snippet that saves meds to specific user:
const {userId, medName, medDescription, dose, medType, date, time} = req.body;
try {
const newMed = new MedsSchema({
userId,
medName,
medDescription,
dose,
medType,
date,
time,
});
await newMed.save().then(() => res.send({response: 'ok'}));
const specificUser = await User.findById({_id: userId});
specificUser.medicines.push(newMed);
await specificUser.save().then(
User.findOne(specificUser)
.populate('medicines')
.exec(function (err, docs) {
if (err) return handleError(err);
console.log(docs);
}),
);
Here's the userSchema:
const userSchema = new mongoose.Schema(
{
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
phone: {
type: Number,
required: true,
},
email: {
type: String,
unique: true,
required: true,
},
medicines: [{type: mongoose.Schema.Types.ObjectId, ref: 'MedsSchema'}],
},
{
toJSON: {
virtuals: true,
},
},
);
router.get('/getMeds/:Id', (req, res) => {
console.log(req.params.Id);
MedsSchema.find({userId: req.params.Id}, function (err, result) {
if (err) {
res.send(err);
} else {
res.send(result);
}
});
});
what do i add to this that will make me get only specific medicines for that specific user instead of getting all medicines?
Can you edit your first code snippet to
const { userId, medName, medDescription, dose, medType, date, time } = req.body;
try {
const user = await User.findOone({ _id: userId });
const newMed = await MedsSchema.create({
userId: user,
medName,
medDescription,
dose,
medType,
date,
time,
});
const specificUser = await User.findByIdAndUpdate({ _id: userId }, { $push: { medecines: newMed } });
return res.json({ newMed, specificUser })
};
and in the router
router.get('/getMeds/:Id', async (req, res) => {
console.log(req.params.Id);
const user = await User.findOne({ _id: req.params.Id }).populate({ path: 'medicines' })
console.log(user.medicines)
return res.json({meds: user.medicines})
});
also check the console results to see if everything is working

Routing in NodeJs

I am working on an eCommerce application, and I am trying to save users in my database but when I hit the API in the postmen then instead of :
res.json({
name: user.name,
email: user.email,
id: user._id
});
});
**instead of this code following code is running
user.save((err, user) => {
if (err) {
return res.status(400).json({
err: "NOT able to save user in DB"
});
}
//the complete code of my "auth.js" file is as following:
const User = require("../models/user");
exports.signup = (req, res) => {
const user = new User(req.body);
user.save((err, user) => {
if (err) {
return res.status(400).json({
err: "NOT able to save user in DB"
});
}
res.json({
name: user.name,
email: user.email,
id: user._id
});
});
};
exports.signout = (req, res) => {
res.json({
message: "User signout"
});
};
///and the complete code of my user model file is as following:
var mongoose = require("mongoose");
const crypto = require("crypto");
const uuidv1 = require("uuid/v1");
var userSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
maxlength: 32,
trim: true
},
lastname: {
type: String,
maxlength: 32,
trim: true
},
email: {
type: String,
trim: true,
required: true,
unique: true
},
userinfo: {
type: String,
trim: true
},
encry_password: {
type: String,
required: true
},
salt: String,
role: {
type: Number,
default: 0
},
purchases: {
type: Array,
default: []
}
},
{ timestamps: true }
);
userSchema
.virtual("password")
.set(function(password) {
this._password = password;
this.salt = uuidv1();
this.encry_password = this.securePassword(password);
})
.get(function() {
return this._password;
});
userSchema.methods = {
autheticate: function(plainpassword) {
return this.securePassword(plainpassword) === this.encry_password;
},
securePassword: function(plainpassword) {
if (!plainpassword) return "";
try {
return crypto
.createHmac("sha256", this.salt)
.update(plainpassword)
.digest("hex");
} catch (err) {
return "";
}
}
};
module.exports = mongoose.model("User", userSchema);
SO please anyone tell me how to solve this problem while hiting this code to api mongo shell is also opend and mean while i also keep ROBO3T connected.

Resources