I am using mongoose ODM and have a schema which looks like this:
var banSchema = new Schema({
userid: { type: String, required: true, unique: true },
name: String,
groupid: String,
reason: String,
timestamp: Date
});
I want to output every single user id from all documents in the collection. I am using this query to obtain the userid objects. However I cannot seem to get the full list automatically. I have to manually enter the object number as seeen below:
bot.onText(/\/sync/i, function (msg) {
var fromId = msg.from.id;
var chatId = msg.chat.id;
if (fromId == config.sudo) {
console.log('Sudo Confirmed And Authorized!');
Ban.find({}, function (err, obj) {
console.log(obj[0].userid); // Returns A Single ID
console.log(obj[1].toObject().userid); // Returns a different ID
bot.sendMessage(chatId, obj[1].toObject().useridid);
});
} else {
console.log('Someone Is Trying To Act Like Sudo! *sigh*');
bot.sendMessage(chatId, 'You Are Not A Mod!');
}
});
This however does not return a full list of id's as I want. How could I solve this issue?
The code above is for a telegram bot which on a /sync command it should return a message with all ids from the collection.
Telegram bot API Limits
Due to the API limits, the entire output should be in a single message.
var query = Ban.find({}).select({
"userid": 1,
//Add more column fields here
"_id": 0 //Ensures _id is not displayed
});
var arr = [];
query.exec(function (err, results) {
if (err) throw err;
results.forEach(function (result) {
arr.push(result.userid);
// Add more column fields here;
});
var fixedJoin =arr.join("\n");
console.log(fixed);
bot.sendMessage(chatId, 'List\n\n' + fixedJoin);
});
The easiest way to get all values of a particular field across all docs in the collection is to use distinct:
Ban.distinct('userid', function (err, userids) {
// userids is an array containing all userid values in the collection.
// string.join into a single string for the message.
bot.sendMessage(chatId, 'USER IDs\n\n' + userids.join('\n'));
});
Use this syntax
Ban.find({}).
select('userid').
exec(function(err, result) {
//result is array of userid of all document
});
You can use this syntax:
Ban.find({}, 'userid', function(err, users) {
users.forEach(function(user) {
console.log(user);
bot.sendMessage(chatId, 'users \n' + user);
});
})
Related
I've got a requirement where I need to assign a SharePoint task to two users. Code below assigns it to one user but not the second when creating a task.
first user value _spPageContextInfo.userId second user value taskcase.Caseownername,
$scope.createTask = function() {
var item = $scope.taskDetails;
var taskcase = $scope.caseDetails;
var updates = angular.extend({}, {
Title: item.Title,
DueDate: item.DueDate ? moment(item.DueDate, 'DD/MM/YYYY').format() : null,
Status: item.Status,
AssignedTo: _spPageContextInfo.userId && taskcase.Caseownername,
RelatedCase: $routeParams.id
});
ModalDialog.showWaitScreen({
message: 'Creating task for case ' + updates.Title
}).then(function (waitScreen) {
return CaseManagementService.createTask({
updates: updates
}).then(function (task) {
$log.info('task created', task);
$scope.taskDetails = {
Status: 'Not Started'
};
$scope.loadRelatedTasks();
return ModalDialog.delayClose(waitScreen, 200);
}, function(e){
console.error(e);
});
});
};
You need get the userid from the taskcase.Caseownername object, and then pass the data like below.
AssignedToId: {'results':[_spPageContextInfo.userId,user2Id]}
Refer to: How to update Person field with multiple values using REST API
_spPageContextInfo.userId sounds like an integer value and taskcase.Caseownername sounds like a string value
Is AssignedTo a string? Then just do:
AssignedTo: _spPageContextInfo.userId + taskcase.Caseownername,
This will save both values as 1 string
Is it an integer? You can't save two values in 1 property...
I want to define a put method by using findOneAndUpdate() on a mongoDB object using AngularJS. I am able to successfully do GET and POST operations but I am having difficulty defining PUT. Below is my db object defined in app.js file:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testing23');
var idObj = Schema({
_id: String,
name : {
firstname : String,
lastname : String
},
phones : [Number],
emails : [String],
friends : [String]
});
var Error = mongoose.model('Error', idObj );
My GET and POST are below:
app.get('/api/info',function(req,res){
Error.find(function(err,infos){
if(err)
return res.send(err);
return res.json(infos);
});
});
app.post('/api/info',function(req,res){
Error.create(req.body, function(err,infos){
if(err)
return res.send(err);
return res.json(infos);
});
});
For PUT I am using below method but it is not working:
app.put('/api/infos/:id',function(req,res){
Error.findOneAndUpdate({_id: req.params.id},req.body,function(err,infos){
if(err)
return res.send(err);
return res.json(infos);
});
});
How can I successfully do a PUT operation?
As per the Mongoose Docs your find and modify command should look like the following
Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)
For the example you provided and say you want to update the name, it would be
Error.findOneAndUpdate({_id: req.params.id},{ $set: { name: req.body }},{new: true},function(err,updatedInfos){
if(err)
return res.send(err);
return res.json(updatedInfos);
});
Using {new:true} means the updated document gets returned.
I am using Node and Mongoose, and trying to set an array of ISODate elements:
"visitLog" : [
ISODate("2017-10-22T22:43:49.571Z"),
ISODate("2017-10-22T22:44:39.572Z"),
ISODate("2017-10-22T23:35:36.111Z"),
ISODate("2017-10-22T23:48:26.516Z"),
ISODate("2017-10-22T23:50:33.378Z"),
ISODate("2017-10-22T23:53:56.227Z"),
ISODate("2017-10-22T23:57:20.986Z")
]
So I had an existing schema where visitLog field did not existed, added new field to a schema - visitLog: [ {type: Date, default: '' }],and it worked - the result is what you see above.
But when I created a new document with updated schema that already has an empty array in it - "visitLog" : [ ] , $push just stopped working.
Here is mongoose query, if needed:
// conditions is a ternary operator that checks whether req.body username
// is an email or not, and puts needed condition to a query
var conditions = (!/^[a-zA-Z0-9\-\_\.\+]+#[a-zA-Z0-9\-\_\.]+\.[a-zA-Z0-9\-\_]+$/.test(req.body.username)) ? ' {email: req.body.username } ' : ' {username: req.body.username } ';
var fieldsToSet = {
$push: {
visitLog: new Date().toISOString(),
}
};
var options = { upsert: true };
User.findOneAndUpdate(conditions, fieldsToSet, options, function(err, user) { ...
The working document was created in mongo console, while the second was generated on a server, but I can't how can this make any difference.
Using $push shuld work with empty arrays. Can someone explain what's wrong here?
Thank you.
Edit
It figures that using findByIdAndUpdate without conditions works for both documents:
var fieldsToSet = {
$push: {
visitLog: new Date().toISOString(),
}
};
var options = { new: true };
req.app.db.models.User
.findByIdAndUpdate(req.user.id, fieldsToSet, options, function(err, user) {
You can do with the following query.
User.findOne(condiitons, (err, user) => {
if (user) {
var date = new Date().toISOString();
user.visitLog.push(date);
user.save();
...
}
});
I have a User model and each user document has name field which is String and friends field which is an array of integers which holds id's of other users who this user is friends with.
Whenever I want to create a new user document with one id already in friends array, I have to three steps: 1. create new user with specific name; 2. save this user; 3. update this user's friends field by adding new friend id to the array.
I was wondering if there is another, more efficient way of achieving the same result. Here is my code so far:
var User = mongoose.model('User',{
friends: {
type: [Number],
required: false
},
name: String
});
//cretae new user document
var user = new User ({
name: name
});
user.save(function(err){
if(err){
console.log("something went wrog, read below");
console.log(err);
}else{
User.update({'name': name}, {
$addToSet: { 'friends': newFriendId}
},function(err, count) {
if(err){
console.log(err);
}else{
console.log(count);
}
});
}
});
var User = mongoose.model('User',{
friends: {
type: [Number],
required: false
},
name: String
});
//cretae new user document
var user = new User ({
name: name,
friends : [newFriendId]
});
user.save(function(err){
if(err){
console.log("something went wrog, read below");
console.log(err);
}else{
}
});
I am creating a MEAN Stack application. My post function is as follows:
app.post('/updateGroup/:id', function(req, res) {
var id = req.params.id; // = mongoDB ObjectID ie: "55616e2a37e8728266ceac6"
var vals = {};
vals['hostName'] = req.body.hostName // = a String ie, "Steve"
// this is a different name value than the
// current hostName key that is in
// the groupList db
db.groupList.update(
{"_id": id},
{$set : vals},
function(err, result) {
if (err) {
console.log(err);
}
else {
console.log(result);
}
}
);
});
When I access this function in my front-end Angular code my
console.log(result);
Comes out as:
{ ok: true, n: 0, updatedExisting: true }
But I should see n: 1 to indicate there was an update? Why is my Node application not updating my mongoDB key:value pair?
Is there something about db.collection.update() that I'm missing?
I was able to figure it out:
When assigning the _id query I needed to do it like this:
id['_id'] = mongojs.ObjectId(req.params.id);