Update boolean with Mongoose - angularjs

I have created an app where i can create a to do list. And i have a status that is false when created. The status i supposed to represent if the object done or not.
My mongoose schema look like this in server.js:
// Create mongoose schema
var issueSchema = mongoose.Schema ({
issue: String,
date: String,
status: Boolean,
});
// Create mongoose model
Issue = mongoose.model('Issue', issueSchema);
When i press my button in on my index.html im using angular to send the id trough to the server.js file.
// API PUT ========================
app.put('/issueList/:id', function(req, res){
var id = req.params.id;
Issue.findById(id, function(err, Issue) {
console.log("Object with ID: " + id); // Correct ID
// I need code here
});
});
I need help updating the boolean value to true if false or false if true. Or should i skip the boolean value and use something else?

You can find the issue by id and then save it back to MongoDB after making the changes in success callback.
Issue.findById(id, function(err, issue) {
issue.status = !issue.status;
issue.save(function (err) {
if(err) {
console.error('ERROR!');
}
});
});
I am not sure about the possibility of toggling boolean field atomically as of now in MongoDB.

First, i dont think you should use same variable name outside and inside the function. In this case Issue is same, change it to issue.
And you can try this to update.
Issue.findById(id, function(err, issue) {
console.log("Object with ID: " + id); // Correct ID
issue.status = !issue.status;
issue.save(function(err,result){...});
});
});

Related

How to get return value from Mongoose save function using axios in React JS?

I am new to React JS and I created a simple application which accept UserName and Email and inserts to MongoDB.
I use React + Node + Express + Mongoose + MongoDB and I was able to insert the record successfully
DB.js
router.route("/insert").post(function(req, res) {
let comments = new Comments(req.body);
console.log(req.body)
comments.save();
});
App.js
axios.post("http://localhost:4000/insert", {
UserName: username,
UserEmail: email,
Comments: comments
})
Now, I want to return 'numRowsAffected' from DB.js to App.js.
Hence, I modified DB.js by adding callback to mongoose save() function
router.route("/insert").post(function(req, res) {
let comments = new Comments(req.body);
console.log(req.body)
comments.save(function(err, comments, numRows) {
if ( err ) {
res.send(err);
}
else {
res.json({ message: 'Comments added', data: numRows });
}
});
});
However, I don't know how to change the code on App.js (ie in axios.post) to fetch the return value from DB.js
Any help is highly appreciated
You can use Mongoose.update() with upsert option set to true instead of Mongoose.save() and read the nModified and nInserted property of update return value.
You can see this post for more detail.

Comparing results from two API calls and returning their difference in MEAN app

EDIT: Since I wasn't able to find a correct solution, I changed the
application's structure a bit and posted another question:
Mongoose - find documents not in a list
I have a MEAN app with three models: User, Task, and for keeping track of which task is assigned to which user I have UserTask, which looks like this:
const mongoose = require("mongoose");
const autopopulate = require("mongoose-autopopulate");
const UserTaskSchema = mongoose.Schema({
completed: { type: Boolean, default: false },
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
autopopulate: true
},
taskId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Task",
autopopulate: true
}
});
UserTaskSchema.plugin(autopopulate);
module.exports = mongoose.model("UserTask", UserTaskSchema);
In my frontend app I have AngularJS services and I already have functions for getting all users, all tasks, and tasks which are assigned to a particular user (by getting all UserTasks with given userId. For example:
// user-task.service.js
function getAllUserTasksForUser(userId) {
return $http
.get("http://localhost:3333/userTasks/byUserId/" + userId)
.then(function(response) {
return response.data;
});
}
// task-service.js
function getAllTasks() {
return $http.get("http://localhost:3333/tasks").then(function(response) {
return response.data;
});
}
Then I'm using this data in my controllers like this:
userTaskService
.getAllUserTasksForUser($routeParams.id)
.then(data => (vm.userTasks = data));
...and because of autopopulate plugin I have complete User and Task objects inside the UserTasks that I get. So far, so good.
Now I need to get all Tasks which are not assigned to a particular User. I guess I should first get all Tasks, then all UserTasks for a given userId, and then make some kind of difference, with some "where-not-in" kind of filter.
I'm still a newbie for all the MEAN components, I'm not familiar with all those then()s and promises and stuff... and I'm really not sure how to do this. I tried using multiple then()s but with no success. Can anyone give me a hint?
You can do at server/API side that will more efficient.
In client side, if you want to do then try below
var userid = $routeParams.id;
userTaskService
.getAllTasks()
.then((data) => {
vm.userTasks = data.filter(task => task.userId !== userid)
});

kinvey fetching and remove not working (AngularJS)

I have this problem with kinvey backend,
I'm trying to fetch data from my collection but it doesn't work for me. here is my code :
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
Can you help me please
If you let run the code you have posted then consider four things:
Make sure you have Kinvey implemented:
<script src="https://da189i1jfloii.cloudfront.net/js/kinvey-html5-sdk-3.10.2.min.js"></script>
Make sure you have initialized the Kinvey service before:
// Values shown in your Kinvey console
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
Make sure you are logged in with a user that has the rights to read your collection (should be fine using the All Users role (default)):
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
})
.catch(function(error) {
console.log (error);
});
Output the return result to see whats coming back. To make sure you do the query AFTER successful login, paste you query inside the .then function of login.
I'm not sure if your query is valid unter 3.x since a lot has changed and I'm not working with older Kinvey versions.
So that all together would look like this:
// Initialize Kinvey
Kinvey.init({
appKey: '<your_appKey>',
appSecret: 'your_appSecret'
});
// Login with already registered user
var promise = Kinvey.User.login('<username>', '<password>')
.then(function() {
console.log ("You are logged in");
// Your query
var query = new $kinvey.Query();
query.equalTo('_id', '5909e8084c68b1ef74fa4efc');
var dataStore = $kinvey.DataStore.collection('User1Bases', $kinvey.DataStoreType.Network);
var stream = dataStore.find(query);
stream.subscribe(function onNext(entity) {
// Output of returning result
console.log (entity);
// ...
}, function onError(error) {
// ...
}, function onComplete() {
//...
});
})
.catch(function(error) {
console.log (error);
});
There are now three return sets possible:
Nothing (as you say) -> Something missing/wrong in the code (compare yours with mine)
Empty array: Your query didn't find anything, adapt the search value(s)
One or more entries in the array -> All fine, what you were looking for!
Hope that helps!
When querying by _id there is a built in method: http://devcenter.kinvey.com/angular/guides/datastore#FetchingbyId
Try switching to var stream = dataStore.findById('entity-id');
Also check to make sure you don't have any preFetch or postFetch BL that is interfering with the query.

Posting Schema.Types.ObjectId arrays to MongoDB

How can I post an array of Schema.Types.ObjectId (s) to MongoDB? I'm trying to create User Groups, which is a group of the 'User' Model e.g.
var UserGroup = new Schema({
users: [{
type: Schema.Types.ObjectId,
ref: 'User'
}]
});
New UserGroup Function
module.exports.create = function(request, response) {
var group = new UserGroup({
users = request.body.users
});
group.save(function(error) {
if(error) { throw error; } else { response.send('Group Created Successfully.');
});
};
I'm currently using Postman to test the functionality, how exactly should the data be posted?
As a Javascript array i.e ['A_USER_ID', 'A_USER_ID'] ?
Thanks!
#Answer
I was using the older syntax of the select() function, and therefore was passing invalid parameters to the $push function. When sending the request, I simply pass the ObjectIds as id,id,id and once they get to the server, simply put it into an array using var my_array = request.body.users.split(','); and then push it to the database using the following:
$push: { users: { $each: my_array } }
I hope this was helpful, the documentation isn't particularly clear on this matter.

How to do a query using dot( . ) through Mongoose in Node.js and How to add an empty array

I have the following schema:
var userSchema = new Schema({
userID: Number,
userName: String,
userEmail: String,
teams:Array,
socialMedias:
{
fbUID: String,
googleUID: String,
twitter: String }
});
First, How can I add an empty array? Is it right the way I am doing in the following?
teams:{},
Second, I am trying to do a query using Mongoose in my Node.js but I am getting an error in the dot ('.'):
This is my document I am saving:
var user = new users({
userID: id, //give the id of the next user in Dbase
userName: userName,
userEmail: 'userEmail',
teams:{},
socialMedias: [{socialMediaType: socialMediaID}]
});
where userName, socialMediaType and socialMediaID are parameters of a function.
So, after I add this doc, I am trying to do the following query:
function searchUser(socialMediaID, socialMediaType){
var user
users.findOne({socialMedias.socialMediaType: socialMediaID}, function(err, userFound){
if(err) return handleError(err);
user = userFound;
});
//what does MongoDb return if it does not find the document?
return user;
}
but I am getting an error in this :
socialMedias.socialMediaType
So, how can I do this query?
I tried to find in Mongoose Documentation but I did not find.
Thank you for your understanding.
There's a number of issues here that you are likely running into.
First, teams is an array property, but you're assigning an object to it. You need to do something like this:
var user = new users({
userID: id, //give the id of the next user in Dbase
userName: userName,
userEmail: 'userEmail',
teams:[],
socialMedias: [{socialMediaType: socialMediaID}]
});
Second, if socialMediaType is passed in as a function param, you can't use it like you're doing. You need to do something like this:
var socialMedias = {};
socialMedias[socialMediaType] = socialMediaID;
var user = new users({
userID: id, //give the id of the next user in Dbase
userName: userName,
userEmail: 'userEmail',
teams:[],
socialMedias: [socialMedias]
});
Third your findOne is not going to work as is. From what I can gather of your intention here, you need something like this:
function searchUser(socialMediaID, socialMediaType){
var user
var query = {};
query["socialMedias."+socialMediaType] = socialMediaID;
users.findOne(query, function(err, userFound){
if(err) return handleError(err);
user = userFound;
});
//what does MongoDb return if it does not find the document?
return user;
}
But fourth, even that won't work because you are synchronously returning user from a method that performs and asynchronous operation. There are various ways to solve that, but you can start by reading up about promises, or passing a callback function into searchUser.

Resources