I am trying to connect MongoDB with nodejs and fetching data from MongoDB server and showing into the HTML page which has Datatable. So the Fetching of data is occurring on the server side.I am successfully getting the data from MongoDB and paginate them with the help of Paginate-v2 plugin. But now the search is not working of datatable. Pagination -v2 has one function name populate to do searching in datatable but it's not working for me. Please help me with this. Below is my Node JS code.
NodeJs code
app.get('/gettable',(req,res)=>{
console.log(req.query);
user.find({}).populate({
select:'name',
match: { 'name': 'Graiden Waller' }
}).exec((err, user) => {
console.log(user.name) ;
}).paginate({},{
page:Math.ceil(req.query.start / req.query.length) + 1,
limit:parseInt(req.query.length),
populate:{
match:{
name:'Graiden Waller'
}
}
},function(err,result){
console.log(result);
var mytable = {
draw:req.query.draw,
recordsTotal:0,
recordsFiltered:0,
data:[],
}
if(err) {
console.log(err);
res.json(mytable);
} else {
if(result.totalDocs > 0) {
mytable.recordsTotal = result.totalDocs;
mytable.recordsFiltered = result.totalDocs;
for(var key in result.docs) {
mytable.data.push([
result.docs[key]['name'],
result.docs[key]['lastname'],
result.docs[key]['email'],
result.docs[key]['pass'],
result.docs[key]['birthdate'],
result.docs[key]['zipcode'],
result.docs[key]['phonenumber'],
]);
}
}
res.json(mytable);
} });
Whenever I use populate, it showing me this error Cannot read property 'count' of undefined I don't know what should I write for searching in a data table.Please help me for this issue.
Related
I am trying to get data from Mongo DB by filtering a nested object.
the collection structure is :
{
"id":"8820624457",
"type":"CreateEvent",
"actor":{
"id":27394937,
"login":"Johnson0608",
"display_login":"Johnson0608",
"gravatar_id":"",
"url":"https://api.github.com/users/Johnson0608",
"avatar_url":"https://avatars.githubusercontent.com/u/27394937?"
},
"repo":{
"id":163744671,
"name":"Johnson0608/test",
"url":"https://api.github.com/repos/Johnson0608/test"
},
"payload":{
"ref":"master",
"ref_type":"branch",
"master_branch":"master",
"description":null,
"pusher_type":"user"
},
"public":true,
"created_at":"2019-01-01T15:00:00Z"
}
I am trying to get data by repo id.
my code is :
collection.find({'repo.id':id}).toArray(function(err, docs) {
console.log(id);
assert.equal(err, null);
console.log("Found the following records");
console.log(docs);
res.status(200).json({docs});
callback(docs);
});
but I am getting empty array, would be grateful is someone can point me to the right direction
MongoDB compares types before values. If your id comes from req.params it's probably passed as string while repo.id seems to be a number. Try to convert your value to number:
const id = +req.params.repoId
I am trying to get form data from MongoDB server and showing it into data table using nodeJs.I successfully have done server-side pagination using npm Paginate v-2 plugin. But now the searching is not working. Below is my NodeJs and javascript files code. Please help me for searching.
NodeJs code
app.get('/gettable',(req,res)=>{
console.log(req.query);
user.paginate({},{
page:Math.ceil(req.query.start / req.query.length) + 1,
limit:parseInt(req.query.length)
},function(err,result){
var mytable = {
draw:req.query.draw,
recordsTotal:0,
recordsFiltered:0,
data:[],
}
if(err) {
console.log(err);
res.json(mytable);
} else {
if(result.totalDocs > 0) {
mytable.recordsTotal = result.totalDocs;
mytable.recordsFiltered = result.totalDocs;
for(var key in result.docs) {
mytable.data.push([
result.docs[key]['name'],
result.docs[key]['lastname'],
result.docs[key]['email'],
result.docs[key]['pass'],
result.docs[key]['birthdate'],
result.docs[key]['zipcode'],
result.docs[key]['phonenumber'],
]);
}
}
res.json(mytable);
}
});
DisplayTable.Js code
$(document).ready(function(){
$('#example').DataTable({
"processing": true,
"serverSide": true,
"ajax": "http://localhost:8080/gettable"
});
})
As I said, I am successfully getting data from a server and showing into data table with server-side pagination but searching is not working but in searching div whatever I search, I am getting that value in search array, like this
search: { value: 'svs', regex: 'false' },
_: '1548653540009' }
But its not implementing in datatable to filter columns.
As I said in the comment that search will not work out of the box when server side is enabled in DataTable, it is because now the whole functionality, whether sorting, paging, limit, and search has to be implemented in the server. DataTable will only send the parameter needed for doing the functionality. Following is the code just for your reference, it is not tested and you may get an error also. You may get inputs from the following code. Feel free to edit the following code if in case of getting errors so that it can help future readers.
app.get('/gettable',(req,res)=>{
console.log(req.query);
var query = {},
// array of columns that you want to show in table
columns = ['name', 'lastname', 'email', 'pass', 'birthdate', 'zipcode', 'phonenumber',];
// check if global search is enabled and it's value is defined
if (typeof req.query.search !== 'undefined' && req.query.search.value != '') {
// get global search value
var text = req.query.search.value;
// iterate over each field definition to check whether search is enabled
// for that particular column or not. You can set search enable/disable
// in datatable initialization.
for (var i=0; i<req.query.columns.length; i++) {
requestColumn = req.query.columns[i];
column = columns[requestColumn.data];
// if search is enabled for that particular field then create query
if (requestColumn.searchable == 'true') {
query[column] = {
$regex: text,
};
}
}
}
user.paginate(query,{
page:Math.ceil(req.query.start / req.query.length) + 1,
limit:parseInt(req.query.length)
},function(err,result){
var mytable = {
draw:req.query.draw,
recordsTotal:0,
recordsFiltered:0,
data:[],
}
if(err) {
console.log(err);
res.json(mytable);
} else {
if(result.totalDocs > 0) {
mytable.recordsTotal = result.totalDocs;
mytable.recordsFiltered = result.totalDocs;
for(var key in result.docs) {
var data = [];
for(var column in columns) {
data.push(result.docs[key][column]);
}
mytable.data.push(data);
}
}
res.json(mytable);
}
});
I need help!! I have this code:
router.get("/campgrounds", function(req,res) {
Campground.find({}, function(err, campgrounds) {
if(err) {
console.log(err);
} else {
res.render("campgrounds/index", {campgrounds: campgrounds});
}
});
});
Unfortunately I couldn't find any good examples online.
I wanted index to load different mongo collections after clicking on the link that leads to /campgrounds which I want to change to /:locations_id.
The main page will have 3 links to location1, location2 and location3 respectively.
Is there a way to load a different collection (location 1, 2 or 3) at /:locations_id depending on the link clicked before?
My idea was to use req.params.locations_id and maybe append some info on the clicked link and use it in an if statement in order to load the correct collection.
Thank you very much for your help and I apologize for the extremely conceptual question.
Hmmm, I guess you can pull a trick.
//Put every collection in an array
var collections = [
Campground,
Collection2,
Collection3
];
//When user visits: example.com/campgrounds/1
router.get("/campgrounds/:locationId", function(req,res) {
//Parse the index from the URL
var locId = parseInt(req.params.locationId);
//Make sure that we aren't blown up :)
if(isNaN(locId) || locId > 2) {
//Default collection's index - which is Campground in this example
locId = 0;
}
//Match the given collection by its index and return it
collections[locId].find({}, function(err, campgrounds) {
if(err) {
console.log(err);
} else {
res.render("campgrounds/index", {campgrounds: campgrounds});
}
});
});
I'm trying to update an entries, if they are found in my Mongo DB:
exports.insert = function(project, data) {
data.forEach(function(d){
d.project = project;
var asset = new Asset(d);
Asset.findOne({
project: asset.project,
ip: asset.ip
}, function(err, match) {
if (err) { return next(err); }
if (match) {
console.log('asset found, updating');
match.mac = 'blablah';
match.save();
}
});
});
};
I also tried to update like this:
asset.mac = 'blalah';
match.update(asset);
In both cases my fields don't update in the DB. I see no change.
There may be smarter ways to do this but I need to be able to use save or update to do it for future.
NB: Although findOneAndUpdate may be the preferred way of doing this, I'm really curious to know why save() or update() do not work in my case. I would like to know how to use those methods to update my document.
If you're trying to find one entry and update it, you should use findOneAndUpdate:
Asset.findOneAndUpdate({
project: asset.project,
ip: asset.ip
}, {
mac: 'blablah'
}, function (err, docThatWasUpdated) {
....
})
what's the delete used for? I didn't see such grammar before, can anybody help me?
the code snippet is very easy and it is used the node.js , mongoose , mongodb
function _update(game, callback) {
if (!game) {
callback(new Error("Game must be provided."));
return;
}
if (!game.gameId) {
callback(new Error("Game id should be provided"));
return;
}
var updates = (game instanceof Game) ? game.toObject() : game;
delete updates._id;
updates.modifiedDate = new Date();
Game.findOneAndUpdate({"_id": game.id, "deleted" : {"$ne": true}}, updates, callback);
}
delete in JavaScript removes the property from the object.
var game = {
id: 1
}
console.log(game); // Object {id: 1}
delete game.id
console.log(game); // undefined
It is used to remove a property from an object. So in this instance it removes the _id property from updates