Can't save to mongoDB's database - mongodb

While sending a post request i written the following code :
var email = req.body.email ;
var newDetails = { email: email };
Details.create(newDetails);
console.log(newDetails);
while sending the request. The console.log shows me the correct details,
However in the mongo shell the only collection that exist is "details" and it's empty .
That's the Mongoose Schema:
var mongoose = require("mongoose");
var DetailsSchema = mongoose.Schema({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
I'm using NodeJS.
Thanks in advance.

Your Mongoose Model should be like
const mongoose = require("mongoose");
const Scheme = mongoose.Schema;
const DetailsSchema = new Scheme({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
Node js Code should be like
var detailsModel = require('../model/Details.js');//path of mongoose model
var detailsData = new detailsModel();
detailsData.email = req.body.email;
detailsData.save(function (err, savedJob) {
if (err) {
return res.send(err);
} else {
return res.send(savedJob);
}
});

To save data in mongoDB's Database
You can use this way
var detailsData = new detailsModel();
detailsData.save()
.then(business => {
res.status(200).json({'Details': 'newDetails added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
With this, you can also handle error easily.

Related

react js mongodb query issue

i'm having an issue querying my mongodb database. i'm using react js. the problem doesn't seem to be the connection because i can save to the database just fine, i can only assume its a syntax issue. i've looked around but couldn't find a fix. below is a snippet of code from the schema.js file and the index.js file:
Schema.js
//import dependency
var mongoose = require('mongoose')
var Schema = mongoose.Schema
//create new instance of the mongoose.schema. the schema takes an
//object that shows the shape of your database entries.
var UserSchema = new Schema({
socketId: String
})
//export our module to use in server.js
module.exports = mongoose.model('User', UserSchema)
index.js
var mongoose = require('mongoose')
var db = mongoose.connect('mongodb://mongodatabase', {
useMongoClient: true,
/* other options */
})
var UserSchema = require('../schema/Schemas');
function userExist(userList, username){
var usert = new UserSchema()
var query = usert.where({socketId: username})
query.findOne(function (err, usert) {
if (err) return handleError(err);
if (usert) {
// doc may be null if no document matched
}
});
return username in userList
// return query
}
I get the error : usert.where is not a function.
i tried using just find but i get the same error
any help would be welcome, Thank you
You should use .findOne function directly on your schema class instead of .where
Like this :
UserSchema.findOne({socketId: username}, function (err, usert) {
if (err) return handleError(err);
if (usert) {
// doc may be null if no document matched
}
});
.where must be used on query, not schema.
To use .where, you can do it like this :
User.findOne().where({ socketId: username }).exec( function (err, usert) {
if (err) return handleError(err);
if (usert) {
// doc may be null if no document matched
}
})

MongoDB document not saved but showing success

I have a problem. I'm trying to save answers from a survey. My problem is that I'm sending these answers through axios and they are showing in the console.log from the server, which means that my data is reaching the server safely. But data is not being saved. Also no error is shown.
Server.js
router.route('/answers')
//post answers to database
.put(function(req, res){
var survey = new Survey();
survey.name = req.body.name;
survey.email = req.body.email;
survey.q_id = req.body.q_id;
survey.q_text = req.body.q_text;
survey.answer = req.body.answer;
console.log(Survey.collection)
survey.save(function(err){
if(err){
console.log(err)
return ;
}
res.send(survey);
});
})
Survey.js (Model)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var question = new Schema({
q_text:String,
order: Number,
options:[{
type: {type: String},
value: {type: String}
}]
});
module.exports = mongoose.model('Question',question);
Code that is posting the data
const url = 'http://localhost:3100/api/answers';
axios.put(url, survey)
.then(res => {
console.log('Successfully posted');
console.log(res);
setSubmitting(false);
setStatus({submitted: true});
})
.catch(err => {
console.log(err);
})
Try this :
survey.save(function(err, savedSurvey){
if(err){
console.log(err)
return ;
}
res.send(savedSurvey);
});

check if username and email is unique in database

Tried searching the net for 2 days and still could not find a specific answer. I have the below node.js code for user routes and models. How can I check if the username and email has never appear in the MongoDB, and prompt the user a message if there is?
model:
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
// User Schema
var UserSchema = mongoose.Schema({
username:{type: String , required:true, index: true, unique:true},
email:{type: String, required:true, index: true, unique:true},
password:{type: String, required:true}
});
module.exports = mongoose.model('User', UserSchema)
route:
var express = require('express');
var router = express.Router();
var User = require('../models/user');
var bcrypt = require('bcryptjs');
// Get Homepage
router.get('/', function(req, res){
res.render('index');
});
router.get('/register',function(req,res){
res.render('register');
});
// submit form
router.post('/submit', function(req, res){
// retrieve data from posted HTML form
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password_confirm = req.body.password_confirm;
// express validator
req.checkBody('username','Username is required').notEmpty();
req.checkBody('email','Email is required').notEmpty();
req.checkBody('email','Invalid email').isEmail();
req.checkBody('password','Password is required').notEmpty();
req.checkBody('password','Password must contain at least 6 characters').isLength({min:6});
req.checkBody('password_confirm','Password mismatch').equals(req.body.password);
// store the errors
var errors = req.validationErrors();
if(errors){res.render('register',{errors:errors});}
else {
// hash password
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(password, salt);
password=hash;
// load data into model
var newUser = new User ({username:username, email:email, password:password});
// save the new user
newUser.save(function(err,newUser){
if(err){console.error(err);}
// console.error is same, but in stderr form
else{
console.log('new user saved successfully');
console.log(newUser);
}
});
res.redirect('/');
}
});
module.exports = router;
app.post('/authenticate', function(req, res) {
var user = new User({
username: req.body.username
});
user.save(function(err) {
if (err) {
if (err.name === 'MongoError' && err.code === 11000) {
// Duplicate username
return res.status(500).send({ succes: false, message: 'User already exist!' });
}
// Some other error
return res.status(500).send(err);
}
res.json({
success: true
});
});
})
You have to catch the error and return it to the front end of your application. This code above should demonstrate how to achieve this by using server status 500. Regarding searching the web, this answer and question are quite similar to this previous question:
How to catch the error when inserting a MongoDB document which
violates an unique index?
I hope this helped to some extend.

remove value from mongoDB array

hi i am trying to remove a value from mongoDB but instead of removing a specific value the code is deleting all users from the schema lol.
var mongoose = require('mongoose');
var User = require('../../models/UserModel');
module.exports.unfollow = function(req, res){
var thefollowee = req.body.followee;
var thefollower = req.body.follower;
User.find({_id: thefollower}).remove({following: thefollowee}).exec();
User.find({_id: thefollowee}).remove({followers: thefollower}).exec();
res.json({ message: 'Unfollowed'});
};
the followee is pointing to the id of the person being followed,
the follower is pointing to the id of the user who follows the followee.
ok so i got it by using the $pull method
var mongoose = require('mongoose');
var User = require('../../models/UserModel');
module.exports.unfollow = function(req, res){
var thefollowee = req.body.followee;
var thefollower = req.body.follower;
User.findByIdAndUpdate(thefollowee, { $pull: { followers: req.body.follower }}, function (err, user) {
if (err)
return handleError(err);
});
User.findByIdAndUpdate(thefollower, { $pull: { following: req.body.followee }}, function (err, user) {
if (err)
return handleError(err);
});
res.json({ message: 'Unfollowed'});
};

MongoDB and mongoose schema

This is model in models.js
var PatientSchema = new mongoose.Schema({
_id : String,
LastName : String,
MiddleName : String,
PatientIntId : String,
Sex : String,
Address1 : String,
City : String,
State : String,
ZipCode : String,
AccountNumber : String,
Ssn : String
});
var PatientInfoMdl = mongoose.model('PatientInfo',PatientSchema);
exports.PatientInfoMdl = PatientInfoMdl;
and my code for accessing data is :
var dbObj = require('../dataBase');
var config = require('../config');<
var moment = require('moment');
var models = require('../models/models');
var orm = require('orm');
var xml2js = require('xml2js');
var fs = require('fs');
var user = models.user;
var PatientInfoMdl = models.PatientInfoMdl;
exports.DisplayUsers = function (req, res) {
var name = '';
dbObj.connect(config.get('mongo'), function () {
PatientInfoMdl.find()({}, function (err, docs) {
if (err)
res.json(err);
else res.render('index', { Patients : docs });
});
});
}
and I am not getting data and what is my mistake?
My mistake is not following the naming conventions of collections in mongoDB.
Is there a convention to name collection in MongoDB?
For example:
Controller.js
var mongoose = require('mongoose');
var User = mongoose.model('User');
module.exports = {
show: function(req, res) {
User.find({}, function(err, users) {
res.render('main', {users: users});
})
}
}
Models:User.js
// require mongoose
var mongoose = require('mongoose');
// create the UserSchema
var UserSchema = new mongoose.Schema({
name: String
})
// register the schema as a model
var User = mongoose.model('User', UserSchema);
module.exports = {User}
routes.js
// here we load the Quote model that we created on the server.js page
var mongoose = require('mongoose');
var User = mongoose.model('User');
// import users
var users = require('../controllers/users.js');
module.exports = function(app) {
app.get('/', function(req, res) {
res.send("Hello");
})
app.get('/user',function(req,res){
users.show(req,res);
})
}