Database Query logic - javascript

I'm making 2 queries to the database.
Right now, if even one of them is undefined, I get the generic 'not found' message that is set up. This is because there's an 'else' set up at every DB query where it responds with 'not found' if a value is undefined
What I want to achieve:
If one of them is null, I want to add the value 'nil'.
Example:
field1: nil,
field2: 'value'
If both are null, then I want it to respond with the previously mentioned 'not found' message.
What's a good approach for this?

I think your goal may be achieved using 1 call to the database by using https://www.mongodb.com/docs/manual/reference/operator/aggregation/switch/ but please provide example document structure and what the expected behavior should be in a bit more detailed way.

[
{
_id: new ObjectId("634989627d163a41b75e1e13"),
name: 'Ashish Jain',
address: 'Delhi'
},
{
_id: new ObjectId("634989cc7d163a41b75e1e14"),
name: '',
address: 'India'
},
{
_id: new ObjectId("634989cc7d163a41b75e1e15"),
name: '',
address: ''
},
{
_id: new ObjectId("634989cc7d163a41b75e1e16"),
name: 'Ash',
address: ''
}
]
This is my existing data in the local database.
Following is my Node.js code:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("test");
var all_docs = dbo.collection("ccn1").find({}).toArray(function(err, result) {
if (err) throw err;
for (i in result){
if(result[i]['name'] && result[i]['address']) {
console.log("name: " + result[i]['name'])
console.log("address: " + result[i]['address'])
}
else if (result[i]['name'] && !result[i]['address']){
console.log("name: " + result[i]['name'])
console.log("address: nil")
}
else if (!result[i]['name'] && result[i]['address']){
console.log("name: nil")
console.log("address: " + result[i]['address'])
}
else {
console.log("Not Found")
}
console.log()
}
db.close();
});
});
What you are seeing below the output:
(base) ashish#ashishlaptop:~/Desktop/software/node$ node "Hello World Script For MongoDB Local.js"
name: Ashish Jain
address: Delhi
name: nil
address: India
Not Found
name: Ash
address: nil

Related

Why is mongo saying this is not a valid JavaScript object when I try to use the update method?

I am getting this error when I try to update a record:
(node:2018) UnhandledPromiseRejectionWarning: MongoError: document must be a valid JavaScript object
Heres my code that I'm trying to run:
global.db.collection("groups").find({userId: user_id.toString(), groupNumber:parseInt(realGroupNumber)}).toArray( function (err, group) {
if(err) {console.log(err)};
if(group[0]) {
group[0].students.push(NewRow[row]);
//NOTE: HERE IS WHERE THE ERROR HAPPENS (BELOW)
global.db.collection("groups").update({userId: user_id.toString(), groupNumber:parseInt(realGroupNumber)}), group[0], function (err, group) {
if(err) {console.log(err)};
};
};
});
It keeps saying that group[0] is not a valid JavaScript object, but typeof group[0] returns 'object'.
Also here is an example of group[0] console logged out:
{ _id: 5df7fcc562f67c0a0b66aefd,
userId: '5d3f42db404e9e0a91fdd9d8',
groupNumber: 3,
selectedLeaders: [ '5df7d27e2e5e1904552a30a4' ],
roomNumber: '333',
groupNotes: '',
students:
[ { firstName: 'June',
userId: '5d3f42db404e9e0a91fdd9d8',
lastName: 'Lopez',
gender: 'female',
groupId: 3,
roomNumber: '1234',
_id: 5dfac3a34c64110809726571 } ] }
Any help greatly appreciated! Thanks!
It looks like the error is being caused by the closing parenthesis on line 7 below. This is closing the update, which excludes group[0] and the callback from being included:
global.db.collection("groups").update({
userId: user_id.toString(),
groupNumber: parseInt(realGroupNumber)
}), group[0], // <---- HERE
function(err, group) {
if (err) {
console.log(err)
};
};
Try moving it to the end of the block, after the callback:
//NOTE: HERE IS WHERE THE ERROR HAPPENS (BELOW)
global.db.collection("groups").update({
userId: user_id.toString(),
groupNumber: parseInt(realGroupNumber)
}, group[0],
function(err, group) {
if (err) {
console.log(err)
};
});
That said, note that collection.update() has been deprecated for some time. You should look into updating to at least a 3.X version of the Node driver and using updateOne or updateMany:
https://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#update

Parsing array of data and sending with nodemailer?

I've got an array of data that I want to send in a table using NodeMailer that looks something like:
var results = [ {
asin: 'B01571L1Z4',
url: 'domain.com',
favourite: false,
createdAt: 2016-11-18T19:08:41.662Z,
updatedAt: 2016-11-18T19:08:41.662Z,
id: '582f51b94581a7f21a884f40'
},
{
asin: 'B01IM0K0R2',
url: 'domain2.com',
favourite: false,
createdAt: 2016-11-16T17:56:21.696Z,
updatedAt: 2016-11-16T17:56:21.696Z,
id: 'B01IM0K0R2'
}]
What I am trying to do i to create a loop inside my HTML and then loop through the data. I did try the below, but it seems there are limitations on what I can do.
var sendUpdatedMerch = transporter.templateSender({
from: '"Test" <domain1#gmail.com>', // sender address
subject: 'Test Updates', // Subject line
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>{{result.forEach((item) => {<tr><td>{{asin}}</a></td><td>{{url}</td><td>{{favourite}}</td><td>{{createdAt}}</td></tr>})}}</tbody></table></div>' // html body
});
sendUpdatedMerch({
to: 'domain#gmail.com'
}, {results}, function(err, info){
if(err){
console.log(err);
} else {
console.log('Done');
}
})
Could anyone point out where I am going wrong please and what I need to do to correct my problems.
It seems you have tried to use results.forEach((item) but you placed this inside the quotes 'result.forEach((item)' which is a string and won't execute at all.
You may have used this kind of syntax in your page when you used the view engines like jade, swig etc which will do the parsing for you. But here, you should call them manually to parse this kind of syntax.
Otherwise, you can do the parsing with the array function as below where I have used array.reduce which is handy and will do the parsing nicely.
You can try the same to generate the content and append it to the html as below.
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' +
content + '</tbody></table></div>' // html body
var results = [ {
asin: 'B01571L1Z4',
url: 'domain.com',
favourite: false,
createdAt: '2016-11-18T19:08:41.662Z',
updatedAt: '2016-11-18T19:08:41.662Z',
id: '582f51b94581a7f21a884f40'
},
{
asin: 'B01IM0K0R2',
url: 'domain2.com',
favourite: false,
createdAt: '2016-11-16T17:56:21.696Z',
updatedAt: '2016-11-16T17:56:21.696Z',
id: 'B01IM0K0R2'
}];
var content = results.reduce(function(a, b) {
return a + '<tr><td>' + b.asin + '</a></td><td>' + b.url + '</td><td>' + b.favourite + '</td><td>' + b.reatedAt + '</td></tr>';
}, '');
console.log(content);
/*
var sendUpdatedMerch = transporter.templateSender({
from: '"Test" <domain1#gmail.com>', // sender address
subject: 'Test Updates', // Subject line
html: '<div><table><thead><tr><th>ASIN</th><th>Url</th><th>Favourite</th><th>createdAt</th></tr></thead><tbody>' + content + '</tbody></table></div>' // html body
});
sendUpdatedMerch({
to: 'domain#gmail.com'
}, {results}, function(err, info){
if(err){
console.log(err);
} else {
console.log('Done');
}
})
*/

Finding a document, editing it, and putting it back in MongoDB

I am using mongodb and I want to be able to edit a document and reinsert it WITHOUT duplicates. So far i have tried collection.findAndModify() but I couldn't get that to work. I have a collection like this:
UserProfiles = [
{
userProfileID: 1,
firstName: 'Austin',
lastName: 'Hunter',
email: 'ahun.....com',
token: '',
platform: '',
password: 'incorrect',
companyProfileID: 1,
authentication: '',
UserTopics: [
I want to be able to do this:
1 - grab the profile out of the object via searching for email match.
2 - when the email matches, edit the token and platform item.
3 - then put the document back in with no duplicates. So I can't just insert it again because that duplicates it.
Can anyone help me out on figuring this out?
Code:
function registerUser(email, token, platform) {
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('UserProfile');
collection.findAndModify({
query: { email: email },
update: { token: token, platform: platform }
});
db.close();
modelname.findOneAndUpdate({ email: var_email}, { $set: { token: var_token, platform: var_platform}}, { new: true }, function(err, doc)
{
//doc here has updated document, in case you need it.
});
var_email etc. is your variable name and email is field name in
database.
{ new: true } - This part is used to fetch updated document, you can chose to not have this in your code but then you wont get updated document in response.

output to jade the appropriate value from an object sent from express

I'm trying to figure out how you would retrieve the appropriate information on the page when users go to "/users/:name". what I'm trying to do is print out "welcome user2" if user2 logged in and the same for the other users. the way I was thinking of doing it is to pass along the param from "/users/:name" and check if the param is equal to the username value print out that value.(not sure if that is a safe way to do it) how do I cycle through my particular list of objects and compare it to the param?
I get this sent to my jade document
{ list: 'userList', users: [ { password: 'pass1', username: 'user1' }, { username: 'user2', password: 'pass2' }, { username: 'user3', password: 'pass3' } ], address: '14459 70 th st city NY', desc: '3 floors', __v: 0, _id: 56baf181356641f01213295a }
that get's sent because I do this:
app.get("/users/:name", function(req, res){
// console.log(req.params.name)
User.findOne({"users" : { $elemMatch: { username : req.params.name}}}, function(err, doc){
console.log("test ", doc)
res.render("users", {result : doc, name : req.params.name});
})
})
jade:
html
head
body
p= result
p Welcome #{result.users[0].username} #{name} // prints out--> Welcome user1 user2 ||| when user2 signs in
p= result.address
h3= result.desc
a(href="/logout") logout
Then you probably want to go with this, to select appropriate user object for the given param input:
app.get("/users/:name", function(req, res){
// console.log(req.params.name)
User.findOne({"users" : { $elemMatch: { username : req.params.name}}}, function(err, doc){
console.log("test ", doc)
var users = result.users;
var currentUser = {};
for(var i=0;i<users.length;i++)
if(users[i].username === req.params.name)
currentUser = users[i];
res.render("users", {result : doc, user : currentUser });
});
})

Sails.js Mandrill api error

I'm using the sails-mandrill module for a sails.js app. I'm having trouble sending the email. I keep getting this error:
to must be specified, e.g.:
{ to: { email: "foo#bar.com", name: "Mr. Foo Bar" } }
I have my code formatted exactly like that and can't figure out why its still giving me the error.
var email = require('sails-mandrill');
var recipients = [{
email: 'name#email.com',
name: 'John Smith'
}];
email.send({
to: recipients,
subject: 'Test Email',
html:
'I can\'t wait to see you all in Chicago<br/>' +
'I loe you so much!!!! ',
text: 'text fallback goes here-- in case some recipients (let\'s say the Chipettes) can\'t receive HTML emails'
}, function optionalCallback (err) {
if (err) {
console.log(err);
}
});

Categories