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
Related
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 },
})
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);
}
);
I have this user schema
const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");
const userSchema = new Schema(
{
email: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
required: true
},
name: {
type: String,
required: true
},
website: {
type: String
},
bio: {
type: String
}
},
{
timestamps: {
createdAt: "created_at",
updatedAt: "updated_at"
},
toJSON: { virtuals: true }
}
);
userSchema.virtual("blogs", {
ref: "Blog",
localField: "_id",
foreignField: "author"
});
userSchema.pre("save", function(next) {
const user = this;
if (!user.isModified("password")) return next();
bcrypt.genSalt(10, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function(password, next) {
bcrypt.compare(password, this.password, function(err, isMatch) {
if (err) return next(err);
next(null, isMatch);
});
};
const User = mongoose.model("User", userSchema);
module.exports = User;
I want to send notification to everyone when a user creates a blog or add a comment how can I implement this? should I use triggers?
The strategy behind this
You have multiple users.
You have multiple notifications that might be for a single user, for some users or for all users.
You need a notification "read" entry in the storage, to know if the user has read the notification or not.
I guess this can be easily achieved by using mongodb change streams.
You can see more about here with code examples.
power of mongodb change streams
Basically listen for insert/update operation type and react accordingly.
I'm trying to find a user in my node app with mongoose by using
var User = require('../app/models/user');
function mongoTest() {
var publicAddress = "0x8a6be8979340faa30020b0c1f617d8fd4309679f";
User.findOne({"publicAddress": publicAddress}, (err, user) => {
if (err) {
res.status(500).send(err)
} else {
console.log(user);
}
});
}
and err and user always return null. From other questions here (this and this), this usually seems to be related to mongoose pluralising collections. However, I don't think that's my issue because my users.js has
module.exports = mongoose.model('User', userSchema);
// Have also tried module.exports = mongoose.model('User', userSchema, 'User');
For completeness, users.js is
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// Define the schema for our user model
var userSchema = mongoose.Schema({
local: {
username: String,
password: String,
pictureCaption: String,
publicAddress: String,
contractAddress: String
}
});
Finally, I'm sure that public address exists because I can see it in the mongoDB with Robo 3T.
In your userSchema the publicAddress is part of local object.
var userSchema = mongoose.Schema({
local: {
username: String,
password: String,
pictureCaption: String,
publicAddress: String,
contractAddress: String
}
});
You are trying to find an object with publicAddress but it's actually inside the local object. So you should edit the query as follows to get the result.
User.findOne({"local.publicAddress": publicAddress}, (err, user) => {
if (err) {
res.status(500).send(err)
} else {
console.log(user);
}
});
I'm a newbie, but trying to figure out why my GET request returns an empty array even though I know that the Mongo database collection isn't empty. Each word form in the WordForm collection has a "lexicalform" key whose value is a reference to a LexiconEntry object in that collection. When I submit a GET request with a LexiconEntry ObjectId as a parameter, it returns an empty array in stead of the array contents. Here are my files:
The GET route in my controller:
api.get('/wordforms/:id', (req, res) => {
WordForm.find({lexiconentry: req.params.id}, (err, wordforms) => {
if (err) {
res.send(err);
}
res.json(wordforms);
});
});
The LexiconEntry model:
import mongoose from 'mongoose';
import WordForm from './wordform';
let Schema = mongoose.Schema;
let LexiconEntrySchema = new Schema({
lexicalform: String,
pos: String,
gender: String,
genderfull: String,
decl: String,
gloss: [String],
meaning: String,
pparts: [String],
tags: [String],
occurrences: Number,
wordforms: [{type: Schema.Types.ObjectId, ref: 'Form'}]
});
module.exports = mongoose.model('LexiconEntry', LexiconEntrySchema);
The WordForms model:
import mongoose from 'mongoose';
import LexiconEntry from './lexiconentry';
let Schema = mongoose.Schema;
let WordFormSchema = new Schema({
form: String,
gender: String,
case: String,
number: String,
lexicalform: {
type: Schema.Types.ObjectId,
ref: 'LexicalForm',
required: true
}
});
module.exports = mongoose.model('WordForm', WordFormSchema);
Based on your WordForm schema given above, there is no such property lexiconentry exists in WordForm schema as in your query below.
api.get('/wordforms/:id', (req, res) => {
WordForm.find({lexiconentry: req.params.id}, (err, wordforms) => {
if (err) {
res.send(err);
}
res.json(wordforms);
});
});
The property called lexicalform in WordForm schema resembled the one you are trying above. So, you can change your code as below with this.
api.get('/wordforms/:id', (req, res) => {
WordForm.find({lexicalform: req.params.id}, (err, wordforms) => {
if (err) {
res.send(err);
}
res.json(wordforms);
});
});