MongoDB $where is not working properly - javascript

I have looked around and tried all kinds of docs to be able to get the $where clause in MongoDB to work for me, but it just won't work.
Here is my object:
var UserProfiles = [{
userProfileID: "3f8c553c-3633-4fe9-a007-4346a783450c",
firstName: 'Austin',
lastName: 'Hunter',
email: 'ahunter8....com',
token: '',
platform: '',
password: 'admin',
companyProfileID: "86660a5b-7f61-4238-889d-1cc3087947b9",
authentication: ''
}....
there are several "profiles" inserted into the UserProfiles Object. That is just the first one.
Here is me inserting into the collection:
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('UserProfile');
for (var i = 0; i < UserProfiles.length; i++) {
collection.insert(UserProfiles[i], function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
}
db.close();
});
Now I am trying to search my collection for a passed in email AND companyProfileID. If they both match then return that profile. I thought the $where clause would be best but I can't get it to work.
Here is me trying to find():
function getUserProfile(passInEmail, companyID, callback) {
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('UserProfile');
collection.find({$where: "this.email == passInEmail"}, function(err, result) {
if (err) {
console.log(err);
callback(err);
} else if (result.length) {
console.log(result);
callback(result);
} else {
callback(err);
console.log("No document found");
}
});
db.close();
});
}
I am trying to search the collection and if the object email matches the passed in email and the object companyProfileID matches the passed in companyID then success.

The $where clause in your case in not the best thing.
You should do simply:
//userIdParam ad emailParam are two variables
collection.find({userProfileID: userIdParam, email: emailParam})
.toArray(function(err, result) {
if (err) {
console.log(err);
callback(err);
} else if (result.length) {
console.log(result);
callback(result);
} else {
callback(err);
console.log("No document found");
}
});
Take a look of the doc here

Related

How to delete all documents in DocumentDB using NodeJS?

I have one collection user, which has many different properties.
Q.1 I want to run query with specific query and delete all those documents using nodejs, how can I do that?
Q.2 if I want to delete all documents using nodejs, how can I do this?
async.forEach(orders, function(order, callback) {
client.deleteDocument(colle._self,order, function(err, success) {
if (err) {
callback(err);
} else {
callback(null, success);
}
});
}, function(err, result) {
if (err) {
return respondFailed(res, { 'message': err }, 400);
} else {
respondSuccess(res, null, 0, { message: 'All Orders deleted.' });
}
});
I couldn't find a simple example of bulk delete.
Here is a similar solution working with the #azure/cosmos sdk:
const { resources: users } = await container.items
.query({
query: "SELECT * from u"
})
.fetchAll();
users.map(async usr => {
await container.item(usr.id, usr.pk).delete()
})
Thanks for all your concern. finally I found my mistake.
In my code I was passing coll._self collection link instead of docu._self link.
async.forEach(orders, function(order, callback) {
client.deleteDocument(order._self,order, function(err, success) {
if (err) {
callback(err);
} else {
callback(null, success);
}
});
}, function(err, result) {
if (err) {
return respondFailed(res, { 'message': err }, 400);
} else {
respondSuccess(res, null, 0, { message: 'All Orders deleted.' });
}
});

MongoDB get an item out of db

So i have implemented a mongodb on my nodejs server. And what I have done is store users via:
function insertUser() {
var collection = dbb.collection('user');
var user1 = {name: user, token: token};
collection.insert(user1, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
}
function findUserByName(devName) {
var collection = dbb.collection('user');
collection.find({name: devName}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found: ', result);
selectedUserToken = result.token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}
So result will equal:
Found: [ { _id: 57be1cadc281c03ea116c9ab,
name: 'Austin Hunter',
token: 'dJyXVjMJk08kXWrua8SUjKb....SxACihKZoR53y_wOZmcFNKMmD5q99QNvsp3flL' } ]
My question is, how can I get that token out to equal selectedUserToken so I can send a push notification with gcm? Right now result.token is undefined.
You should use findOne() instead of find() since you only expect a single result back:
function findUserByName(devName) {
var collection = dbb.collection('user');
collection.findOne({name: devName}, function (err, result) {
if (err) {
console.log(err);
} else if (result) {
console.log('Found: ', result);
selectedUserToken = result.token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}
But if you wanted to leave your code as is with the find() you would just retrieve the first element of the resulting array retrieved by find()
function findUserByName(devName) {
var collection = dbb.collection('user');
collection.find({name: devName}).toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found: ', result);
selectedUserToken = result[0].token;
} else {
console.log('No document found');
insertUser();
}
dbb.close();
});
}
Maybe result[0].token, because result is an array of user items.

Callback/Promises implementation for a boolean check

Currently I have the following callback system:
var saveTask = function(err, result) {
if (err) return callback(err, result);
var newid = mongoose.Types.ObjectId();
var task = new Task({
_id: newid,
taskname: req.body.name,
teamid: req.body.team,
content: req.body.content,
creator: req.user.userId
});
task.save(function (err) {
if (!err) {
log.info("New task created with id: %s", task._id);
return callback(null, task);
} else {
if(err.name === 'ValidationError') {
return callback('400', 'Validation error');
} else {
return callback('500', 'Server error');
}
log.error('Internal error(%d): %s', res.statusCode, err.message);
}
});
};
if (req.body.team) {
valTeam.isMember(req.body.team, req.user._id, function (err, done) {
if (err) {
saveTask('403', 'Not the owner or member of this team');
} else {
saveTask(null, true);
}
});
} else {
saveTask(null, true);
}
valTeam.isMember
exports.isMember = function(teamid, userid, callback) {
Team.find({'_id':teamid, $or:[{'creator': userid }, {'userlist': { $in : [userid]}}]}, function(err, result) {
if (err) return err;
console.log(result);
if (!result.length)
return callback('404', false);
else
return callback(null, true);
});
}
In short, if team is sent by POST, I'm checking if the user is member of that ID in valTeam.isMember. Am I using the correct syntax and best method to call back my saveTask function to save the task if the user is part of the team?
This code currently works, but I feel like there should be an easier way to do it? How could I use a promise to achieve the same thing?
Thanks in advance.
It's curious the fact that you create objects instead Schemas. However "every head is a different world", this is my way:
task.save(function(error, data){
if (error) {
trow error;
} else {
//Make whatever you want here with data
});

Combine $push and save in mongoDB

Writing my pet application I met some problem. I'm using nodejs and mongojs library to work with mongo.
I wrote code:
db.users.findOne({_id: ObjectId(id)}, function (err, doc) {
if (err) {
res.status(500).send('Can not find name for user.');
return;
}
userName = doc.userName;
db.notes.findOne({userId: id}, function (err, doc) {
if (!doc) {
db.notes.insert({
userId: id,
userName: userName,
notes: [req.body]
}, function (err, doc) {
if (err) {
res.status(500).send('Server error.');
return;
}
res.json(doc);
});
} else {
db.notes.update({
userId: id
}, {
$push: {
'notes': req.body
}
},
function (err, doc) {
if (err) {
res.status(500).send('Server error.');
return;
}
res.json(doc);
});
}
if (err) {
res.status(500).send('Server error.');
return;
}
});
});
Now it looks like callback hell for me. I try to modify my code to make it more readable and use save method:
users.findOne({_id: makeObjectId(id)}, function (err, doc) {
if (err) {
res.status(500).send('Can not find name for user.');
return;
}
userName = doc.userName;
notes.save({
userId: id,
userName: userName
}, {
$push: {
'notes': req.body
}
}, function (err, doc) {
if (err) {
return res.status(500).send('Error during inserting the note');
}
res.status(200).send(doc);
});
});
Now it looks more readable but doesn't work. Is it possible in MongoDB to combine save method (to make it possible to modify document if it exists and create new if not) and $push for one of parameters?
Thanks in advance.
Bingo!!!
notes.update({
userId: id,
}, {
$set: {
userId: id,
userName: userName
},
$push: {
notes: req.body
}
}, {
upsert: true
}, function (err, doc) {
if (err) {
return res.status(500).send('Error during inserting the note');
}
res.status(200).send(doc);
});
Thanks to Blakes Seven

No access to this from within nested callback

I have the following code:
var Company = function(app) {
this.crypto = require('ezcrypto').Crypto;
var Company = require('../models/company.js');
this.company = new Company(app);
}
// Create the company
Company.prototype.create = function (name, contact, email, password, callback) {
this.hashPassword(password, function(err, result) {
if (err) throw err;
console.log(this.company); // Undefined
this.company.create(name, contact, email, result.password, function(err, result) {
if (err) {
return callback(err);
}
return callback(null, result);
});
});
}
// Get company with just their email address
Company.prototype.hashPassword = function (password, callback) {
if(typeof password !== 'string') {
var err = 'Not a string.'
} else {
var result = {
password: this.crypto.SHA256(password)
};
}
if (err) {
return callback(err);
}
return callback(null, result);
}
module.exports = Company;
The problem is that this.company is undefined on line 11 of that code block.
I know this is not what I think, but I'm not sure how to refactor to get access to the correct this.
so theres 2 solution's to this
first the dirty one
Company.prototype.create = function (name, contact, email, password, callback) {
var that = this; // just capture this in the clojure <-
this.hashPassword(password, function(err, result) {
if (err) throw err;
console.log(that.company); // Undefined
that.company.create(name, contact, email, result.password, function(err, result) {
if (err) {
return callback(err);
}
return callback(null, result);
});
});
}
and the clean one using bind https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
Company.prototype.create = function (name, contact, email, password, callback) {
this.hashPassword(password, (function(err, result) {
if (err) throw err;
console.log(this.company); // Undefined
this.company.create(name, contact, email, result.password, function(err, result) {
if (err) {
return callback(err);
}
return callback(null, result);
});
}).bind(this));
}
You can reference this through another variable by declaring it in the Company.create scope, like this:
// Create the company
Company.prototype.create = function (name, contact, email, password, callback) {
var me = this;
this.hashPassword(password, function(err, result) {
if (err) throw err;
console.log(me.company); // Undefined - not anymore
me.company.create(name, contact, email, result.password, function(err, result) {
if (err) {
return callback(err);
}
return callback(null, result);
});
});
}
Untested, but it should work like this.

Categories