remove value from mongoDB array - mongodb

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'});
};

Related

Can't save to mongoDB's database

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.

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.

How to stop inserting duplicate records before saving in db?

I'm trying to save students records, but it should not take duplicate records. How is it possible? In below code i have tried to do
app.post("/save",function(req,res){
var std=new student(req.body);
student.findOne({},function(err,success){
if(err)
{
console.log(err);
}
else
{
// console.log(success);
std.save(function(err,success){
if(err)
{
console.log(err);
}
else
{
console.log("inserted");
console.log(success);
}
});
}
})
});
Here is the sample code. Please note that the existence of the value in MongoDB database depends on the req.body as mentioned in the OP.
In the below code, I have only name attribute in the Student collection. So, the duplicate check is based on the name attribute only.
You may need to change the code if you would like to check for the specific attribute in the collection to determine the duplicate value.
Please note that my Student collection has only attribute in the schema as well.
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Student = mongoose.model('Student', { name: String });
var app = express();
var bodyParser = require('body-parser');
var app = express();
var urlencoded_body_parser = bodyParser.urlencoded({
extended: true
});
app.use(bodyParser.json());
app.use(urlencoded_body_parser);
app.post("/save", function (req, res) {
console.log(req.body);
var student = new Student(req.body);
Student.findOne(req.body, function (err, success) {
if (err) {
console.log(err);
res.send(err);
}
else {
console.log(success);
if (success == null) {
student.save(function (err, success) {
if (err) {
console.log(err);
res.send(err);
}
else {
console.log("inserted");
console.log(success);
res.send("success");
}
});
} else {
res.send("Student already present");
}
}
})
});
app.listen(3000);
Output:-
First time execution:-
Input:-
{
"name" : "john"
}
Output:-
success
Subsequent executions with the same input json:-
Output:-
Student already present

Query MongoDB to implement typheahead in ui

I am trying to query my MongoDB to find all the matching name fields in the documents of my collection from the typeahead of my angular ui, I have to display the contents of the matched documents in table format, I referred few docs and wrote this API, when I try to test in Advanced REST client , it displays connection timed out, can anyone suggest me where I am going wrong?
My API code
var mongoose = require('mongoose');
var enterprise = mongoose.model('enterprise');
var search = function(req, res){
function searchEnterprise(){
var name = req.params.name;
enterprise.find({"name": '/^'+ name + '$/i'},function(err, data){
if (err){
console.log('err',err);
} else {
res.json(data);
console.log(data);
}
});
}
}
module.exports = {
searchEnterprise : search
};
no need nested function searchEnterprise(). just use it
var search = function(req, res){
var name = req.params.name;
// can also use $regex like bellow line
//enterprise.find({'name': {$options:'i', $regex: name }}, or
// enterprise.find({"name": '/'+ name + '/i'}
enterprise.find({'name': {$options:'i', $regex: name }},function(err, data){
if (err){
console.log('err',err);
return res.status(400).send({msg: "error"});
} else {
console.log(data);
return res.json(data);
// or
//return res.status(200).send(data);
}
});
};
module.exports = {
searchEnterprise : search
};

Having issues posting with express and mongodb

I am trying to post a form through express. For some reason when I am posting, it is posting about 4-8 times. It seems that when autocomplete is involved it using the keystrokes.
I am also using gulp and wanted to know how to post using express or if I should post separately in a javascript file.
Code Example
ADD USER FILE (which is included in my server file)-
var express = require('express');
var passport = require('passport');
var form = require('express-form');
var field = form.field;
var User = require('../models/user');
var router = express.Router({
mergeParams: false
});
router.get('/user/add', function (req, res) {
res.render('users/add', {
user: req.user,
message: req.flash('addUserMessage')
});
});
router.post('/user/add', function (req, res) {
User.findOne({ 'email' : req.body.email }, function (err, user) {
if (err)
res.redirect('/error');
if (user) {
req.flash('addUserMessage', 'This email exists already');
res.redirect('/user/add');
} else {
var newUser = new User();
newUser.email = req.body.email;
newUser.firstName = req.body.firstName;
newUser.lastName = req.body.lastName;
newUser.save(function(err) {
if (err)
throw err;
req.flash('addUserMessage', 'Success');
res.redirect('/user/add');
});
}
});
});