Checking documents from MongoDb with if(==) operator in NodeJs - node.js

I have problem how to check specific document from MongoDb in NodeJs with if operator.
My MongoDb collection looks liket this (I only need document "button"):
{
"_id" : ObjectId("5e95eb9da19c2430d4952754"),
"title" : "Krepšinis",
"author" : "5e90eb1abbcb1f33e8b17720",
"place" : "dsadas",
"count" : 10,
"going_count" : 5,
"button" : "Būsiu",
"__v" : 0
}
My NodeJs:
router.post('/:id', function(req, res){
let post = {};
if(post.button == "Būsiu"){
post.button = "Nebūsiu";
} else {
post.button = "Būsiu";
}
let query = {_id:req.params.id}
Post.update(query, post, function(err){
if(err){
console.log(err);
return;
}
req.flash('success', 'Postas Atnaujintas');
res.send('Success');
});
});
The problem is I don't get any errors, it just doesn't work.
And this is my Ajax:
$(document).ready(function(){
$('.going').on('click', function(e){
console.log('working')
$target = $(e.target);
const id = ($target.attr('data-id'));
$.ajax({
type:'POST',
url: '/posts/'+id,
success: function(response){
alert('Važiuojam');
},
error: function(err){
console.log(err);
}
});
});
});
I don't really know what to try else, because I'm pretty new to programming.

Can you try specifying the mongodb aggregation pipeline and check what the result of affected documents in the query is as below
router.post('/:id', function(req, res){
let post= {};
if(post.button == "Būsiu"){
post.button = "Nebūsiu";
} else {
post.button = "Būsiu";
}
let query = {_id:req.params.id}
Post.update(query, {$set:post}, function(err, response
){
if(err){
console.log(err);
return;
}
console.log(response.result.nModified)
req.flash('success', 'Postas Atnaujintas');
res.send('Success');
});
});

Related

Unable to run a function synchronously in nodejs and express

I have used wikipedia-js for this project. This is my code for summary.js file.
var wikipedia = require("wikipedia-js");
var something = "initial";
module.exports = {
wikitext: function(topicname) {
console.log("Inside wikitex funciton :" + topicname);
var options = {
query: topicname,
format: "html",
summaryOnly: false,
lang: "en"
};
wikipedia.searchArticle(options, function(err, htmlWikiText) {
console.log("Inside seararticlefunciton :");
if (err) {
console.log("An error occurred[query=%s, error=%s]", topicname, err);
return;
}
console.log("Query successful[query=%s, html-formatted-wiki-text=%s]", topicname, htmlWikiText);
something = htmlWikiText;
});
return something;
},
};
This module I am using in /wiki/:topicname route. The corresponding code in index.js is like this.
router.get('/wiki/:topicname', function(req, res, next) {
var topicname = req.params.topicname;
console.log(topicname);
var first = summary.wikitext(topicname);
res.send("Hello "+first);
});
The problem is, everytime i visit a wiki/some-topic, the last return statement of summary.js executes before htmlWikiText is populated with content. So I always see hello initial on the browser page. Although after sometime it gets printed on terminal due to console.log statement.
So how should I resolve this issue?
I'm not going to try turning this code into synchronous. I'll just correct it to work as an asynchronous version.
You need to pass in callback to wikitext() and return the value in that callback. Here is the revised code of wikitext() and the route that calls it:
var wikipedia = require("wikipedia-js");
module.exports = {
wikitext: function(topicname, callback) {
console.log("Inside wikitex funciton :" + topicname);
var options = {
query: topicname,
format: "html",
summaryOnly: false,
lang: "en"
};
wikipedia.searchArticle(options, function(err, htmlWikiText) {
console.log("Inside seararticlefunciton :");
if (err) {
console.log("An error occurred[query=%s, error=%s]", topicname, err);
return callback(err);
}
console.log("Query successful[query=%s, html-formatted-wiki-text=%s]", topicname, htmlWikiText);
callback(null, htmlWikiText);
});
}
};
router.get('/wiki/:topicname', function(req, res, next) {
var topicname = req.params.topicname;
console.log(topicname);
summary.wikitext(topicname, function(err, result) {
if (err) {
return res.send(err);
}
if (!result) {
return res.send('No article found');
}
res.send("Hello "+result);
});
});

res.redirect() not working for me in node.js

I am trying to POST a request for /draft and create a new "draft" / update an existing one in my database. after that I want to instantly redirect to the /draft?id=RELEVANT_ID_HERE page.
this is my current POST request function:
app.post('/draft', function(req,res){
var id = req.query.id;
var postTitle = req.body.head;
var article = req.body.article;
if(id){
db.postCatalog.findOneAndUpdate({_id: id}, {title:postTitle, inShort:article.substring(0,100), content:article}, function(err, data){
if (err) {
return handleError(err);
}
else {
console.log(data);
res.status(200).redirect('/draft?id='+id);
}
});
}
else{
id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
new db.postCatalog({title:postTitle,
_id:id,
author:'temp',
AuthorID:2,
date:'2/3/12',
inShort:article.substring(0,100),
content:article ,
published:false
}).save(function (err, data) {
if (err) {
return handleError(err);
}
else {
console.log(data);
res.status(200).redirect('/draft?id='+id);
}
});
}
});
so, everything works except for the redirect. I am getting the correct GET request in the node console, but nothing happens in the browser.
this is the code for the GET request:
app.get('/draft', function(req,res){
var id = req.query.id;
if(id){
db.postCatalog.findOne({_id: id}, function(err, post){
if(err) {
return handleError(err);
}
else{
if(post){
console.log(post);
res.status(200).render('editDraft.hbs', {post: post});
}
else{
routes._404(req,res);
}
}
});
}
else{
console.log('creating new draft');
res.status(200).render('editDraft.hbs');
}
});
I am using Express and Mongoose. view engine is Handlebars.
Thanks for reading!
I think the status 200 is throwing you off. Try using a 302 and it should work.
res.writeHead(302, {
'Location': '/draft?id='+id
});
res.end();

Node.js — mongoose static method example

I wish to define a method on a model UserModel such that I get the names of all the users that have userId < 10.
Following is my implementation:
// pseudo code
UserModel === {
userId : Number,
userName: String
}
UserSchema.statics.getUsersWithIdLessThan10 = function(){
var usersLessThan10 = []
this.find({userId : {$lt : 10}}, function(error, users){
users.forEach(function(user){
console.log(user.userName) // ... works fine
usersLessThan10.push(user.userName)
})
})
return usersLessThan10
}
I understand why this doesn't seem to work — async find API. But if that's the case, then whats the way to do it? This async stuff is kind of overwhelming.
Add callback and return the users in this callback as follows:
UserSchema.statics.getUsersWithIdLessThan10 = function(err, callback) {
var usersLessThan10 = []
this.find({userId : {$lt : 10}}, function(error, users){
users.forEach(function(user){
console.log(user.userName) // ... works fine
usersLessThan10.push(user.userName)
})
callback(error, usersLessThan10)
})
}
Then call usersLessThan10 with the callback:
... .usersLessThan10(function (err, users) {
if (err) {
// handle error
return;
}
console.log(users);
})
try this:
API code:
var UserApi = require('./UserSchema');
var callback = function(response){
console.log(response); // or res.send(200,response);
}
UserApi.getUsersWithIdLessThan10(callback);
UserSchema code:
UserSchema.getUsersWithIdLessThan10 = function(callback){
var usersLessThan10 = []
this.find({userId : {$lt : 10}}, function(error, users){
if (error)
{ callback(error)}
else{
users.forEach(function(user){
console.log(user.userName) // ... works fine
usersLessThan10.push(user.userName);
//TODO: check here if it's the last iteration
callback(usersLessThan10);
})
}
})
}

mongodb inserting subdocuments as : [Object]

i am inserting data into mongodb using mongodb driver in nodejs.
var mongodb = require('mongodb');
var insert = function(uri, collectionName, data, next) {
mongodb.MongoClient.connect(uri, function(err, driverDb) {
if(err) {
next(err);
} else {
driverDb.collection(collectionName).insert(data,function(err,result) {
if(err) {
next(err);
} else {
driverDb.close(function (err) {
if(err) {
next(err);
} else {
next(null,result);
}
});
}
});
}
});
};
insert('mongodb://localhost/mean-test','testcol',{
a : 'Apple',
b : [ { ba: 'Boy' }, {bb : 'Bird'} ]
}, function(err,models) {
console.log(models);
});
The above result into following:
[{a:'Apple', b : [[Object]] }]
How do i achieve this :
[{_id:ObjectId("someid"), a:'Apple', b : [{_id:ObjectId("someid"), ba: 'Boy' }, {_id:ObjectId("someid"), bb : 'Bird'}] }]
Please note i do not want to use any other npm module except of mongodb.
also i want to insert in one db query.
Your objects are inserting correctly, it's just that console.log only shows two levels of object detail by default. To show all object levels you need to call util.inspect directly so you can control that:
console.log(util.inspect(models, {depth: null}));

Http Route called multiple times

When the following route is called in express, it is actually executed 6 times. The console.log is printed 6 times, and my mongoose logic is executed 6 times (saves 6 time in database).
I then get returned a http 500 from cloud9ide "Could not proxy request". I am really confused, I have no loops in my code, how can this happen? The console.log("in else (2)"); get printed 6 times.
Edit: I have tried the mongooseLogic code with various parts commented out, and the issue was still there. This looks like it isn't a mongoose issue.
Second edit: I have changed the post for get and hardcoded the body that would be sent, and the route was executed only once.
Third edit: I am also using everyauth for session/authentication with the facebook oauth.
app.post("/result/:userId/:elementId", function(req, res) {
var receivedJSON = req.body;
console.log("In route");
//Making sure the receive request is valid
if(typeof(receivedJSON.type) !== undefined) {
mongooseLogic.saveResults(req.params.elementId, receivedJSON, req.params.userId, function(message) {
if(message === "Success") {
res.json({ success: true, message: 'Result saved.'});
}
else {
res.json({ success: false, message: 'Error in saving results. Trace: ' + message});
}
});
}
else {
res.json({ success: false, message: 'Failed, Invalid object sent to server'});
}
});
Code on the mongooseLogic file:
var saveResults = function(elementRefId, receivedResult, userId, callback){
if(elementRefId.toString().length !== 24 ){
callback("Invalid objectId for elementId");
}
else{
Result.findOne({ "id" : userId, "serieResult.id": elementRefId }, function(err, result){
if(err){
callback("No Document found: " + err);
}
else if( result === null){
console.log("in null");
var tempResult = {
id : elementRefId,
unit : receivedResult.unit,
value : receivedResult.value
}
Result.update({ "id" : userId}, { $push: {"serieResult": tempResult}}, {upsert: true}, function(err){
if(err){
callback("Error in saving result (Distance): " + err);
}
else{
callback("Success");
}
});
}
else{
Result.update({ "id" : userId, "serieResult.id": elementRefId },
{ $set:{
"serieResult.$.unit" : receivedResult.unit,
"serieResult.$.value" : receivedResult.value,
},{upsert: true}, function(err){
if(err){
callback("Cant update doc: " + err);
}
else{
console.log("in else (2)");
callback("Success");
}
});
}
});
}
}
}
This was a problem with the Cloud9 proxy that interfered. The problem was adressed thanks to this issue and has been resolved.

Resources