Node JS, How do i get data from a collection with Mongoose - javascript

I'm using MVC. How can I use the method findOne({}) at my loginController?
I just want to get data from my collection. Also that collection is already exist with couple things. All I want, get data from it. By the way I'm sorry for my English.
App.js:
const dbURL = process.env.DB_URL;
mongoose.connect(dbURL, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true })
.then((result) => {console.log('bağlandı'); app.listen(8080);})
.catch((err) => console.log(err))
loginController.js:
const loginControllerPost = async (req, res) => {
db.collection.findOne({req.body.username}) //How to properly use the method?
}

You need to define schemas (tables) to tell mongoose what database structure look like. For example, UserSchema:
const conn = mongoose.createConnection('your connection string');
const UserSchema = new Schema({
name: String,
username: String,
password: String,
}, {
collection: 'users', // define collection name here
});
const UserModel = conn.model('UserModel', UserSchema);
const user = await UserModel.findOne({ username: 'Alice' });

Related

Elasticsearch sync/update after MongoDB document update with Mongoosastic

I am using MongoDB, Mongoose, Elasticsearch and Mongoosastic on a Node project. I have a MongoDB Atlas database and a local Elasticsearch database which are mapped together. When I create a new Document in MongoDB it is created in ES as well, and when I delete it in Mongo it is deleted in ES too. So everything works until this point.
What I did next is, I added an update route to update specific documents in Mongo. They do get updated but the changes are not reflected in ES because I might be missing something. Does anyone have any ideas?
Here is the Model/Schema in donation.js:
const mongoose = require('mongoose');
const mongoosastic = require('mongoosastic');
const Schema = mongoose.Schema;
const donationSchema = new Schema({
donorUsername: {
type: String,
required: true,
es_indexed:true
},
bankName: {
type: String,
required: true,
es_indexed:true
},
qualityChecked: {
type: String,
required: true,
es_indexed:true
},
usedStatus: {
type: String,
required: true,
es_indexed:true
},
}, { timestamps: true });
donationSchema.plugin(mongoosastic, {
"host": "localhost",
"port": 9200
});
const Donation = mongoose.model('Donation', donationSchema , 'donations');
Donation.createMapping((err, mapping) => {
console.log('mapping created');
});
module.exports = Donation;
Here are the create and update functions/routes in donationController.js:
const donation_create_post = (req, res) => {
console.log(req.body);
const donation = new Donation(req.body);
donation.save()
.then(result => {
res.redirect('/donations');
})
.catch(err => {
console.log(err);
});
}
const donation_update = (req, res) => {
const filter = { donorUsername: req.body.donorUsername };
const update = { bankName: req.body.bloodbankName,
qualityChecked: req.body.qualityChecked,
usedStatus: req.body.usedStatus };
Donation.findOneAndUpdate(filter, update)
.then(result => {
res.redirect('/donations');
})
.catch(err => {
console.log(err);
});
}
Solved it. Added {new: true} in Donation.findOneAndUpdate(filter, update, {new: true}).

Reflecting Changes To Mongo DB After New Post Request - Mongoose & Nodejs

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 },
})

is there a method to execute a function after a spesific condition in express js

for exemple I have a user model like this
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
username: {
type: String,
required: true,
},
Points: {
type: Number,
default: 0,
},
module.exports = User = mongoose.model("users", UserSchema);
then I want to execute a function automatically when user.points is equal to 10 with express js, is there any solution ?
#Yessine, may you should try something like this. You can add checkForPoints wherever you are updating the Points and proceed with your things,
const { Users } = require('/schema.js');
const checkForPoints = async (username) => {
await Users.findOne({ username }, function (err, data) {
if (err) {
console.log("enter error ------", err)
}
if (data && data.Points === 10) {
// Execute your code
}
});
};
// Users schema(schema.js)
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('your db', { useNewUrlParser: true });
const requestSchema = mongoose.Schema({
_id: mongoose.Types.ObjectId,
username: String,
Points: Number
});
module.exports = mongoose.model('users', requestSchema);
Polling is a technique where we check for fresh data over a given interval by periodically making API requests to a server.enables you to periodically check for the newest values of data and do further requests once it enters the desired state.

Async/Await - Node - Express - Mongo

I'm working on a project that uses a node/express API and Mongo for storage. I have a function that tries to retrieve data from the storage using the code in the screenshot below. My understanding of async/await is that at the point of await, code execution will pause and proceed when the promise is resolved.
However, the data returned by the function (in the screenshot) is always null, although, the record is there in the db. [The slug is also passed correctly.]
I am starting to believe I am missing something regarding the concept of async/await.
Could anyone please assist me with this?
Am I doing something wrong here?
The calling function is as follows:
async create(req, res, next) {
debug(chalk.blue(`*** Create RSVP`));
console.log(req.body.event); //event is defined and matches db
const event = await Event.findBySlug(req.body.event);
console.log(event); // logs null here
}
Called function:
async function findBySlug(slug) {
return await Model.findOne({ slug: slug })
.populate('user')
.populate('category')
.exec();
}
I have run your code, findBySlug should be working fine. below is sample code for you.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/database-name', {useNewUrlParser: true});
const UserSchema = new mongoose.Schema({
username: String
})
const CategorySchema = new mongoose.Schema({
name: String
})
const PostSchema = new mongoose.Schema({
content: String,
author: {
type: ObjectId,
ref: 'User'
},
category: {
type: ObjectId,
ref: 'Category'
}
})
const Post = mongoose.model('Post', PostSchema, 'posts');
const User = mongoose.model('User', UserSchema, 'users');
const Category = mongoose.model('Category', CategorySchema, 'categories');
async function findBySlug() {
return await Post.findOne({ content: "content name" })
.populate('author')
.populate('category')
.exec();
}
(async function run() {
const event = await findBySlug();
console.log(event); // logs not null here
}())
updating your findBySlug method like this will be enough.
function findBySlug(slug) {
return Model.findOne({ slug: slug })
.populate('user')
.populate('category')
.exec();
}

my node.js user registration is not working with "/auth/registration" but works with "/registration"

I get error cannot POST /auth/auth/register with my code but when I change
app.get('/auth/register')toapp.get('/register') the code works fine. Can anyone please tell me where the problem is and it would be a great help if anyone help me in solution .
I have tried changing app.get('/auth/register') to other routes like ('/create/registration'), app.get('/Registering/user') but it doesn't work .Should I should use only app.get('/userRegister') or app.get('createNewUser') or app.get('goodRegister')
const express = require('express');
const expressEdge = require('express-edge');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const userController = require('./controllers/createUser');
const storeUserController = require('./controllers/storeUser');
const app = new express();
app.get('/auth/register', userController);
app.post('/users/register', storeUserController);
const User = require('../database/models/User')
}
//my controller
module.exports = (req, res) => {
User.create(req.body, (error, user) => {
res.redirect('/')
})
}
//my database model
const bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
})
UserSchema.pre('save', function(next) {
const user = this
bcrypt.hash(user.password, 10, function(error, encrypted) {
user.password = encrypted
next()
})
})
module.exports = mongoose.model('User', UserSchema);
app.listen(4000, () => {
console.log("application listening on port 4000")
})
//my view
<form action="users/register" method="POST" encType="multipart/form-data">
I have solved this problem myself. thanks to everyone for taking out time to check through and give one explanation or another.
the problem with the code is the path to my controller. the name of the file should not have been User but user so I changed const User = require('../database/models/User') to const User = require('../database/models/User') in other to match with the name of the file under the database/model directory

Categories