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
});
Related
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.' });
}
});
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
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.
function(dataValue, cb) {
req.app.db.models.User.find({
_id: { $ne: dataValue._id }
}, function(err, totalUser) {
if (!err) {
var len = totalUser.length;
if (len !== 0) {
req.app.utility.async.map(totalUser, function(each, callback) {
console.log(each);
req.app.utility.async.mapSeries(each.nonregisterContact, function(element, callback1) {
console.log('element', element.number);
console.log('dataValue', dataValue.mobileNumber);
console.log('kolka', Number(element.number) === Number(dataValue.mobileNumber));
if (Number(element.number) === Number(dataValue.mobileNumber)) {
each.registerContact.push(dataValue._id.toString());
each.nonregisterContact.splice(element, 1);
each.save(function(err, finalResult) {
if (!err) {
} else {
console.log(err);
}
})
callback1(null, null);
} else {
callback1(null, null);
}
}, function(err, final) {
if (!err) {
callback(null, null);
} else {
console.log(err);
}
});
}, function(err, result) {
if (!err) {
console.log('2');
return cb(null, dataValue);
} else {
console.log(err);
}
});
} else {
return cb(null, dataValue);
}
} else {
cb(err);
}
})
}
I don't get any response after each.save method call in the mapSeries method final callback.I am trying this solution.How i will do the same thing. How I resolve that and handle this kind of situation?
I tried to simplify code, but I'm not sure that my code realizes your needs. Also I cann't test it :D
dataValue, each, element, finalResult are very common names, so you should use them with caution to keep code is readable/supportable.
// very bad idea is include other libraries to app
var async = require('async');
var db = require('db'); // this module must export connection to db
...
function (dataValue, cb) {
// processUser use data from closure of current function => inside of current
function processUser (user, callback) {
async.mapSeries(user.nonregisterContact, function(contact, callback){
// Check and exit if condition is not satisfied. It's more readable.
if (Number(contact.number) !== Number(dataValue.mobileNumber))
return callback(null); // ignore user
user.registerContact.push(dataValue._id.toString());
user.nonregisterContact.splice(contact, 1);
user.save(function(err, finalResult) { // Is finalResult ignore?
if (err)
console.log(err);
callback(); // ingnore error
})
}, callback);
db.models.User.find({_id: { $ne: dataValue._id }}, function(err, userList) {
if (!err)
return cb(err);
if (userList.length == 0)
return cb(new Error('Users not found'));
// use named function to avoid stairs of {}
async.map(userList, processUser, cb);
})
};
I'm a little new to Express/Node.js/Mongoose and I've ran into callback hell. What I'm trying to do is get a request in to this API URL /page/module/add/:id, if successful call buildMod(data), then that function calls getMod(data), and then that function calls writeMod(data) and eventually I want to pass the true value right back up to my router.
Once I have the response, I want to return it. I've searched online and there's not many similar situations--I personally think I've got myself in too deep...
router.get('/page/module/add/:id', function(req, res) {
Client.find({"emailAddress": emailAddress, "sequence.slug": pageSlug},
{"emailAddress": 1, "sequence.$": 1}, function (err, data) {
if (!err) {
res.statusCode = 200;
buildMod(data);
return res.json(data);
} else {
res.statusCode = 500;
log.error('Internal error(%d): %s', res.statusCode, err.message);
return res.json({
error: 'Server error'
});
}
}).select('sequence emailAddress domain');
});
function buildMod(data) {
getMod(data);
}
function getMod(data) {
Module.find({ 'module_id': moduleNumID }, function (err, module) {
if(!module) {
return false;
}
if (!err) {
writeMod(data);
} else {
return false;
}
});
}
function writeMod(data) {
fs.appendFile(location, content, function(err) {
if (err) throw err;
return true;
});
}
I know the declarations are wrong for the functions for callbacks but I've been trying and I just can't seem to get past this stage. I'm sure this is definitely possible, any help is really appreciated!
fs.appendFile is asynchronous and you can not return from asynchronous calls.
Make use of callback
router.get('/page/module/add/:id', function(req, res) {
Client.find({
"emailAddress": emailAddress,
"sequence.slug": pageSlug
}, {
"emailAddress": 1,
"sequence.$": 1
}, function(err, data) {
if (!err) {
res.statusCode = 200;
buildMod(data, function(data) {
res.json(data);
});
} else {
res.statusCode = 500;
log.error('Internal error(%d): %s', res.statusCode, err.message);
return res.json({
error: 'Server error'
});
}
}).select('sequence emailAddress domain');
});
function buildMod(data, cb) {
getMod(data, cb);
}
function getMod(data, cb) {
writeMod(data, cb);
}
function writeMod(data, cb) {
fs.appendFile(location, content, function(err) {
if (err) throw err;
cb(true);
});
}