Query MongoDB to implement typheahead in ui - mongodb

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

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.

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

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

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

How do I send a Mongo Document back to the front end?

//router
app.get('/retrieve_report', function(req, res) {
var retrieved = retrieve_report(req, res);
res.render('retrieve_report.ejs', {
'report' : retrieved
});
});
//Load up the report model
var Report = require('../models/report');
console.log('Report ' + Report.schema);
//expose this function to our app using module.exports
//query
module.exports = function(req, res) {
//console.log('param ' + res.send);
var query = Report.findById(req.param('id'), function(err, doc) {
if(err) {
throw err;
}
else {
console.log('doc ' + JSON.stringify(doc));
res.send(doc);
}
});
}
//app.js
var retrieve_report = require('./config/retrieve_report');//which is the above code
I want to return the document to the router so that I can put its information into my view. I tried "res.json(doc), but that gave me the error, "throw new Error('Can\'t set headers after they are sent.');" Everyone says to use a callback function, but aren't I using a callback function here?
As your error says:
but that gave me the error, "throw new Error('Can\'t set headers after they are sent.');"
Means you are trying to send data the twice.
Sample code:
app.get('/retrieve_report', function(req, res) {
var query = Report.findById(req.param('id'), function(err, doc) {
if(err) {
throw err;
}
else {
console.log('doc ' + JSON.stringify(doc));
res.send(doc);
}
});
This should work..