I'm sorry, I'm having a hard time even formulating the question properly. Hopefully it's not too confusing.
I'm building a One To Many Relations in my Mongo DB Atlas. I'm using mongoose and Nodejs.
I'm trying to create a One User to Many Entries. For now let's just say it's a one to one, to remove a layer of complexity. One User To One Entry.
All the code in the backend works, but in short the issue I have is that.
Whenever I make a post request to create a new entry, I can include the user ID that the entry belongs to in the request. But whenever I make a post request to create a new user, I can't include an entry ID in the request, because no requests exist yet for that user. When I create a new entry, mongo db doesn't automatically update the document, to add that new entry to the user associated with it. And I don't know what I need to do on my end to get it to dynamically update the users to include new entries that belong to them.
Here are my models/schemas for users and entries, so you can see the association.
USER SCHEMA
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
email: {type: String,
required: true,
unique: true,
displayName: String,
password: {type: String, required: true},
entry: {type: mongoose.Schema.Types.ObjectId, ref: 'Entry', required: true}
}, {collection: "users"});
module.exports = mongoose.model("User", userSchema);
ENTRY SCHEMA
const mongoose = require('mongoose');
const entrySchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: {type:String},
body: {type:String, required: true},
user: {type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true},
entryImage: {type: String}
}, {collection: 'entries'});
module.exports = mongoose.model('Entry', entrySchema);
Here are my routes for users and entries. You can see how I set up the logic for the associations
USER ROUTES
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/user');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
router.get('/:userId', (req, res, next) => {
const id = req.params.userId;
User.findById(id)
.select("_id email displayName password entries")
.populate('entry')
.exec()
.then(user => {
res.status(200).json({
id: user._id,
email: user.email,
password: user.password,
entry: user.entry
})
})
.catch(err => {
error: err
})
})
router.post('/signup', (req, res, next) => {
User.find({email: req.body.email})
.exec()
.then(user => {
if(user.length >= 1){
return res.status(422).json({
message: "Username already exists!"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if(err){
return res.status(500).json({
error: err
});
} else {
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: req.body.email,
displayName: req.body.displayName,
password: hash
});
user.save()
.then(data => {
res.status(201).json({
message: "Your user information has been saved in our records",
id: data._id,
email: data.email,
displayName: data.displayName
})
})
.catch(err => {
res.status(500).json({
error: err
})
})
}
})
}
})
.catch(err => {
res.status(500).json({error : err})
})
}); //End of signup post request
EXAMPLE OF AN ENTRY POST REQUEST
EXAMPLE OF A USER POST REQUEST
Please let me know of you have any other questions. Thank you so much, in advance!
The problem is in your schema. You specified explicitly about the _id field.
Your current scheme does not allow mongoose to create this id automatically.
Well, there are two options:
Simplest way. Simply remove _id field from your schema. Mongoose will automatically generate this for you in every create request.
If you want to specify this, pass an option to mongoose so that it can auto-generate this for you
const userSchema = mongoose.Schema({
_id: { type: Schema.ObjectId, auto: true },
})
Related
so I have to Schemas. PostSchema and UserSchema
const mongoose = require("mongoose")
const PostSchema = new mongoose.Schema({
content: {
type: String,
required: true,
},
likes: {
type: Number,
required: true
},
rescreams: {
type: Number,
required: true
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
createdAt: {
type: Date,
default: Date.now
}
})
module.exports = mongoose.model("Post", PostSchema)
UserSchema:
const bcrypt = require("bcrypt");
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
userName: { type: String, unique: true },
email: { type: String, unique: true },
password: String,
});
// Password hash middleware.
UserSchema.pre("save", function save(next) {
const user = this;
if (!user.isModified("password")) {
return next();
}
bcrypt.genSalt(10, (err, salt) => {
if (err) {
return next(err);
}
bcrypt.hash(user.password, salt, (err, hash) => {
if (err) {
return next(err);
}
user.password = hash;
next();
});
});
});
// Helper method for validating user's password.
UserSchema.methods.comparePassword = function comparePassword(
candidatePassword,
cb
) {
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
cb(err, isMatch);
});
};
module.exports = mongoose.model("User", UserSchema);
My question is: I'm trying to reference the User Object ID in the Post Schema. As you can see, I've done that with type: mongoose.Schema.Types.ObjectID. And I've seen this multiple times. But in my database, the User never shows up in the Document. What do I need to do?
Cheers
There is a difference between referencing a document and embedding a document.
If you want to store a document inside a document you should embed it, thus read operations will be faster because you won't need to perform JOIN operations.
Whereas referencing means storing an ID of an entity that you are referencing, when you need to access the document you are referencing, you need to fetch it from the collection by the ID you have stored. It is slower than embedding, but it gives you higher consistency and data integrity because the data is stored once at the collection and not duplicated at every object. And MongoDB does not support foreign keys so you should be careful with referencing.
So when you are storing the document using ref, you need to put an ObjectID as a user and then fetch the document you need to add populate call. e.g.
PostShema.findOne({ _id: SomeId }).populate('user');
try to save in a variable:
const UserId = UserSchema.Schema.Types.ObjectId;
for more information:
https://mongoosejs.com/docs/api/schema.html#schema_Schema.Types
I have a JSON web token that once it's verified gives me a string that is the object id value of a user I want to find but it seems that every time I try to query with it being parsed into a mongoose object ID it never find my user, am I parsing it right ? I always get a 401 invalid token paylaod
logRoute.get('/user', (req, res) => {
let token = req.body;
User.findOne({_id: mongoose.Types.ObjectId(jwt.verify(token.token, 'secretkey').subject)}, (error, user) => {
if (error) {
console.log(error)
} else {
if (!user) {
res.status(401).send('invalid token payload')
} else {
let userData = {firstname: user.firstname, lastname: user.lastname, type: user.type}
res.status(200).send(userData)
}
}
})
})
my user data
{
"_id": {
"$oid": "5efc7d60ba7a8d3db08ca767"
},
"type": "teacher",
"firstname": "arandomfirstname",
"lastname": "arandomlastname",
"login": "random1",
"pwd": "arandompassword"
}
and
console.log(jwt.verify(req.body.token, 'P3GPROJECT'))
return me
{ subject: '5efc7d60ba7a8d3db08ca767', iat: 1593690718 }
EDIT:
User model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
_id: String,
pwd: String,
lastname: String,
firstname: String,
type: String
});
module.exports = mongoose.model('user', userSchema, 'user');
You've to remove _id: String from model schema, since You've ObjectId as a value (not a string) and it makes mongoose to convert Your input to string, instead of ObjectId.
so:
const userSchema = new Schema({
_id: String,
pwd: String,
lastname: String,
firstname: String,
type: String
});
becomes:
const userSchema = new Schema({
pwd: String,
lastname: String,
firstname: String,
type: String
});
or You can keep it as string but have to define the logic of generation of proper _id:
const uuid = require('short-uuid');
const userSchema = new Schema({
_id: {
type: Schema.Types.String,
default: uuid.generate(), // this will generate unique string
},
pwd: String,
lastname: String,
firstname: String,
type: String
});
P.S. Keep in mind if You want to use _id: String, You've to remove old documents or convert them manually to be {_id: "id here"} instead of {_id: ObjectId("id here")}.
Bonus:
Also I recommend You to create middlewares and separate token handling, from user authorization check.
It will allow You to not repeat access token checking in every request and will help You to understand in which step You're doing it wrong.
And then to do what You want.
jwt.verify throws error if it's invalid, that's why I put try catch arount.
I'm extracting subject as userId and if it does not exist it also means that token invalid, otherwise I pass handling to next handler in routing.
authorizeUser gets req.accessToken.userId from previous middleware and tries to check if user exists. If yes - so it stores complete user object in req.user, otherwise will end with 401 also.
and at last route handling goes last step which does logic or it can be empty as res.status(200).send(req.user)
const checkAccessToken = (req, res, next) => {
try {
const {subject: userId} = jwt.verify(req.body.token, 'secretkey');
if (!userId) throw new Error('Token data does not contain user id');
req.accessToken = {userId};
next();
}
catch (error) {
console.error(error);
res.status(401).send({message: 'Invalid access token'});
}
};
const authorizeUser = async (req, res, next) => {
try {
const user =
await User.findById(req.accessToken.userId)
.select('_id firstname lastname type')
.lean();
if (!user) {
return res.status(401).send({message: 'Unauthorized'});
}
req.user = user;
req.user.id = req.accessToken.userId;
next();
}
catch (error) {
console.error(error);
res.status(500).end();
}
};
logRoute.get(
'/user',
checkAccessToken, // checking token and putting user id to `req.user.id`
authorizeUser, // checking if user exists in database and putting it as `req.user` object
async (req, res) => { // handling some logic or simply returning `req.user` object
// some extra logic here...
res.status(200).send(req.user);
}
);
Basically I wanna create a Post that has its author to the users name, the one who created it. I also want the Post to be pushed into the array of posts, which the user model has, that is ref'ing to "Post".
I have been googling and watching youtube videos but still i do not understand how i would go about to do this, also i read about populate, but i wanna create a new post and have the author to be the users name, also i want the post to be pushed into the array of posts that the user has.
How would I go about doing this ?
This is the post create controller
exports.postCreatePost = (req, res, ) => {
const {
title,
description,
context
} = req.body;
const post = new Post({
title,
description,
context,
author:
})
}
This is the model.js
const mongoose = require("mongoose"),
Schema = mongoose.Schema,
bcrypt = require("bcryptjs");
const postSchema = new Schema({
title: String,
description: String,
context: String,
author: {
type: Schema.Types.ObjectId,
ref: "User"
}
});
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true
},
posts: [{
type: Schema.Types.ObjectId,
ref: "Post"
}]
});
userSchema.pre("save", async function save(next) {
const user = this;
if (!user.isModified("password")) return next();
const hashedPassword = await bcrypt.hash(user.password, 10);
user.password = hashedPassword;
next();
});
const Post = mongoose.model("Post", postSchema);
const User = mongoose.model("User", userSchema);
const userId = new mongoose.Types.ObjectId();
Either let client send you username/id and get it from req.body or when you are authenticating user simply pass the reference to the user to the body of request.
For example when client gives you id/username you can do something like this
const post = new Post({
title,
description,
context,
author: req.body.username or req.body.id
})
If you want to push use this
await findOneAndUpdate({_id: req.body.id}, {
"$push":
{
"posts": post._id
}
})
I'm new to Express/Mongoose and backend development. I am attempting to use a Mongoose subdocument in my Schema and POST data from a form to an MLab database.
I am successfully POSTing to the database when only using the parent Schema, but when I attempt to also POST data from the subdocument I am getting an undefined error. How do I properly POST data from a subdocument?
Here is my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bookSchema = new Schema({
bookTitle: {
type: String,
required: true
},
author: {
type: String,
required: true
},
genre: {
type: String
}
});
const userSchema = new Schema({
name: String,
username: String,
githubID: String,
profileUrl: String,
avatar: String,
// I've tried this with bookSchema inside array brackets and also
//without brackets, neither works
books: [bookSchema]
});
const User = mongoose.model('user', userSchema);
module.exports = User;
Here is my route where I attempt to POST to the database:
router.post('/', urlencodedParser, (req, res) => {
console.log(req.body);
const newUser = new User({
name: req.body.name,
username: req.body.username,
githubID: req.body.githubID,
profileUrl: req.body.profileUrl,
avatar: req.body.avatar,
books: {
// All of these nested objects in the subdocument are undefined.
//How do I properly access the subdocument objects?
bookTitle: req.body.books.bookTitle,
author: req.body.books.author,
genre: req.body.books.genre
}
});
newUser.save()
.then(data => {
res.json(data)
})
.catch(err => {
res.send("Error posting to DB")
});
});
Figured it out. I wasn't properly accessing the values using dot notation.
books: {
// All of these nested objects in the subdocument are undefined.
//How do I properly access the subdocument objects?
bookTitle: req.body.books.bookTitle,
author: req.body.books.author,
genre: req.body.books.genre
}
No need to access .books inside of the books object. req.body.books.bookTitle should be req.body.bookTitle and so forth. Leaving this post up in case it helps someone else.
I'm currently building a Node backend with MongoDB / Mongoose and I seem to be having some problem with tying my data together. Specifically, I wish for all users to be able to submit a form (question form) which will then be added to the "questions" collection. In addition to being added to the questions collection, I also need to store a reference to all of the questions a user has answer directly inside of the user object.
Below you can check out my code. Whenever I make a POST requestion to /questions, it spits out this error. I should note that it successfully adds documents into the questions collection, and each question contains the ID of the user who created it, but the main problem is the user's questions array is not getting updated to include an ID value of submitted questions.
Models/User.js
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt-nodejs');
const UserSchema = new Schema({
email: {
type: String,
lowercase: true,
unique: true,
required: true
},
password: {
type: String,
required: true
},
profile: {
firstName: { type: String },
lastName: { type: String }
},
questions: [
{
type: Schema.Types.ObjectId,
ref: 'Question'
}
],
role: {
type: String,
enum: ['Member', 'Client', 'Owner', 'Admin'],
default: 'Member'
},
resetPasswordToken: { type: String },
resetPasswordExpires: { type: Date }
},
{
timestamps: true
});
/** Pre-save of user to database,
hash password if password is modified or new
*/
module.exports = mongoose.model('User', UserSchema);
Models/Question.js
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
// Schema defines how questions will be stored in MongoDB
const QuestionSchema = new Schema({
questionString: String,
answer: Boolean,
_createdBy : [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
],
},{
//user timestamps to save date created as .createdAt
timestamps: true
});
module.exports = mongoose.model('Question', QuestionSchema);
Controller/QuestionController.js
const jwt = require('jsonwebtoken'),
crypto = require('crypto'),
Question = require('../models/question'),
User = require('../models/user'),
config = require('../config/main');
function setQuestionInfo(request) {
return {
_id: request._id,
questionString: request.questionString,
answer: request.answer,
user: request.user
}
}
exports.addQuestion = function(req, res, next) {
User.findById(req.user.id, (err, user) => {
if (err) throw new Error(err);
// We create an object containing the data from our post request
const newQuestion = {
questionString: req.body.questionString,
answer: req.body.answer,
// in the author field we add our current user id as a reference
_createdBy: req.user._id
};
// we create our new post in our database
Question.create(newQuestion, (err, question) => {
if (err) {
res.redirect('/');
throw new Error(err);
}
// we insert our newQuestion in our posts field corresponding to the user we found in our database call
user.questions.push(newQuestion);
// we save our user with our new data (our new post).
user.save((err) => {
return res.send('sucess!');
});
})
});
}
Router.js
module.exports = function(app) {
// Initializing route groups
const apiRoutes = express.Router(),
userRoutes = express.Router(),
authRoutes = express.Router(),
questionRoutes = express.Router();
//=========================
// Auth Routes
//=========================
/** ROUTES BELOW WORK FINE -- ONLY DEALS WITH POST TO /questions
*
app.use middle ware sets /auth as auth route (everything goes through /api/auth)
apiRoutes.use('/auth', authRoutes);
apiRoutes.get('/dashboard', requireAuth, function(req, res) {
res.send('It worked! User id is: ' + req.user._id + '.');
});
// Set user routes as a subgroup/middleware to apiRoutes
apiRoutes.use('/user', userRoutes);
// View user profile route
userRoutes.get('/:userId', requireAuth, UserController.viewProfile);
// Test protected route
apiRoutes.get('/protected', requireAuth, (req, res) => {
res.send({ content: 'The protected test route is functional!' });
});
// Registration route
authRoutes.post('/register', AuthenticationController.register);
// Login route
authRoutes.post('/login', requireLogin, AuthenticationController.login);
*/
// Problem Area --> Making POST req to /questions
apiRoutes.post('/questions', requireAuth, QuestionController.addQuestion);
// Set url for API group routes
app.use('/api', apiRoutes);
};
You've your schema defined to accept question ids for a user.
questions: [
{
type: Schema.Types.ObjectId,
ref: 'Question'
}
After you save with Question.create(newQuestion, (err, question)... the callback attribute question has the updated data, one with the ObjectId.
Now you add this ObjectId value to your existing questions array that you got from findById on User model.
user.questions.push(question._id);
Mongoose will use the questionId to fill your question object when you use populate on questions array, but thats part for retrieving information.