I can't figure out how I delete data in another MongoDB scheme when I create.
I'm running on mean.js stack.
exports.create = function(req, res) {
var sign = new Sign(req.body);
sign.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
sign.timesheets.forEach(function(entry) {
console.log(entry._id);
});
res.jsonp(sign);
}
});
};
Here I make a call to create a sign. Sign includes some strings and an array 'timesheets' with timesheet objects.
I also got a scheme for timesheets, I want to delete all timesheets objects that are included in my sign from timesheets scheme.
Here is my timesheets delete controller:
exports.delete = function(req, res) {
var timesheet = req.timesheet;
timesheet.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(timesheet);
}
});
};
How do I call this from min sign controller, for each timesheet in sign?
Edit:
Route:
module.exports = function(app) {
var sign = require('../../app/controllers/sign.server.controller');
var timesheets = require('../../app/controllers/timesheets.server.controller');
app.route('/sign')
.post(sign.create, timesheets.deleteAll);
delete all
exports.deleteAll = function(req, res) {
var timesheet = req.timesheet;
timesheet.timesheets._id.forEach(function(entry) {
entry.remove(function(err) {
console.log(entry);
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(entry);
}
});
});
};
It runs and I can see id in the console, but it doesn't delete anything.
If you've implemented this as an array of TimesheetSchema documents inside each SignSchema document, then deleting the parent document would take everything that's part of it with it.
If you stored it as an array of ids referencing a document in another collection, then you'd have to go through those one by one and remove them as well. But I think it's better to go with the first approach if you don't need to do anything fancy. This was you can handle the removal easily, and it makes better sense semantically and performance-wise to retrieve everything you need to handle a "sign" in one go.
Related
I'd like to remove an object element from my user object, I'm using pull to remove it, but it returns
TypeError: user.company.pull is not a function
router.put('/reset', passport.authenticate('jwt', {session:false}), (req, res, next)=> {
user = req.user;
var id_student = user.id;
var id_company = user.company;
var results = [];
User.findById(id_student, function(err, user) {
if(err) {
console.log(err);
return res.status(500).send({message: "Error"});
}
if(!user) {
return res.status(404).send({message: "User Not Found"});
}
user.company.pull({'company': id_company});
res.send(user);
});
});
Effectively, user.company.pull is probably undefined, rather than the function that you're looking for.
If user.company doesn't exist, then user.company is going to be undefined, and there's not a pull method defined on undefined. This means that you're effectively trying to call undefined.pull({'company': whatever}), which will never work.
Try adding a guard to ensure that you have a company attached to a user, in the same way you check to ensure that the user exists. For example:
if (!user.company) {
return res.status(404).send({ message: 'Company not found'});
}
Use 'use strict'; at top of js files.
Read https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode for more information
Check if variable user has property copmany or not and handle it.
Use this condition
if(!user || !user.hasOwnProperty('company')) {
return res.status(404).send({message: "User Not Found"});
}
This is my first attempt at deleting data in a MongoDB database. I'm loosely following this tutorial (just the delete part) to no avail, https://www.airpair.com/javascript/complete-expressjs-nodejs-mongodb-crud-skeleton. I just want to delete all the requested people who are in the requested country. All of my other requests work so I will just post the code that I know is not working, everything else is fine.
EDIT
The error I get in the log is "404 Not Found". When testing w/ Postman the response I get is, "Cannot DELETE /deletepeople/USA/John"
app.delete('deletepeople/:country/:name', function(req, res) {
var countryReq = req.params.country;
var nameReq = req.params.name;
peopleModel
.find({"country":countryReq}, function(err, country) {
country.find({"name": nameReq}, function (err, person) {
person.remove(function (err, person) {
if (err) {
console.log(err);
res.status(500).send();
}
return res.status(200).send();
})
})
})
});
});
country.find({"name": nameReq}, function (err, person) {
The above line is causing you an error, what are you searching in a returned document? Its just an document and not a collection.
You can use the id() method in embedded docs:
Look at the subdocuments [http://mongoosejs.com/docs/subdocs.html]
{ text: undefined,
done: false,
_id: 529e16025f5222dc36000002,
__v: 0 }
PUT /api/todos/529e16025f5222dc36000002 200 142ms - 68b
I keep getting this error when trying to do an update for my simple CRUD todo list. When I submit the update, the change doesn't appear on screen, although the put says it's a 200. Not sure what steps to take so that I don't get this "undefined" error and so I can have the update show up on screen.
EDIT: Included more code
This is the back-end node code:
app.put('/api/todos/:_id', function(req, res) {
Todo.findById(req.params._id, function(err, todos){
todos.text = req.body.text;
console.log(todos);
todos.save(function() {
if (!err) {
res.send(todos);
} else if (err) {
res.send(err);
}
Todo.find(function(err, todos) {
if (err)
res.send(err);
res.json(todos);
});
});
});
});
This is the Angular front-end code:
$scope.updateTodo = function(id) {
$scope.newItem = prompt("Please enter your new item:", "");
$http.put('/api/todos/' + id, {formData: $scope.newItem}).success(function(data) {
$scope.todos = data;
});
$http.get('/api/todos').success(function(data) {
$scope.todos = data;
});
};
I think it's because of this:
$http.put('/api/todos/' + id, { formData: $scope.newItem} )
^^^^^^^^
You're passing a single formData parameter with the request, yet in your Express code, you use this:
req.body.text
Either try this:
req.body.formData.text
Or don't use the formData parameter at all and pass $scope.newItem directly.
Besides that, your Express code is a bit messy: it might send back multiple responses and it doesn't check for errors on the save (as #PaulGray also pointed out).
I have no problem retrieving all my models from the database and displaying them on page using this code:
index: function(req, res) {
Applicant.find(function(err, applicants) {
if (err) {
return console.log(err);
}else{
res.view({
apps: applicants
});
}
});
}
But, if I try to pull just one model and display it, my browser gets stuck on loading. This is the code that I use for pulling just one model:
display: function(req, res) {
Applicant.find().where({id: 2}).done(function(err, appl) {
if (err) {
return console.log('HAI');
}else{
res.view({
applicant: appl
});
}
});
}
Likely, your browser is stuck because an error happens when you're trying to find an Applicant, and your code doesn't return any response in this case. So browser waits for response forever.
Please try something like this
if (err) {
console.log('HAI');
return res.send(err, 500);
}
P.S. By the way, as of Sails v0.9, find() method will alwals return an array, even if only one record is found. If you want to find just one record by id, and expect single object in your view, you can use findOne() method.
.find() returns an array. You may be expecting a single applicant object.
Using appl[0] would solve this. Please note that Sails' Waterline ORM provides .findOne() for situations such as these. Here's more info on .findOne()
display: function(req, res) {
Applicant.find().where({id: 2}).done(function(err, appl) {
if (err) {
return console.log('HAI');
}else{
res.view({
applicant: appl[0]
});
}
});
}
Or better yet...
display: function(req, res) {
Applicant.findOne({id: 2}, function(err, appl) {
if (err) {
return console.log('HAI');
}else{
res.view({
applicant: appl
});
}
});
}
I'm trying to have a total message count for a user's inbox displayed within my layout. I was thinking that I needed to use Express' dynamicHelpers to do this, but in Express <= 2.x, these are not async calls, and I need to do some async processing within them: in this case, a database call with a callback.
I'm trying the following to place the count within my session, which itself is put in a dynamicHelper accessible to the views. However, due to the asynchronous nature of these callbacks, session.unreadMessages is always undefined.
messageCount: function(req, res) {
var Messages = require('../controllers/messages'),
messages = new Messages(app.set('client'));
if(req.session.type === 'company') {
messages.getCompanyUnreadCount(req.session.uid, function(err, result) {
req.session.unreadMessages = result[0].unread;
});
} else if(req.session.type === 'coder') {
messages.getCoderUnreadCount(req.session.uid, function(err, result) {
req.session.unreadMessages = result[0].unread;
});
}
return;
}
Is there another or better way to perform this task?
It should be noted that req.session.unreadMessages is defined (at least within that callback), but undefined when session is called using the helper.
Not sure, it it would be a 'best way', but I'm used to using a filter (or a so called middleware) to load data before it reaches the actual destiny, like in:
filters.setReqView = function(req,res,next) {
req.viewVars = {
crumb: [],
flash_notice: augument,
}
somethingAsync(function(err,data){
req.viewVars.someData = data
next()
})
}
app.all('*', filters.setReqView )
// then on my request:
...
res.render('auth/win', req.viewVars )
Refactoring your code you would have:
app.all('*', function(req, res, next) {
if(req.session && req.session.type){
var Messages = require('./controllers/messages'),
messages = new Messages(app.set('client'));
if(req.session.type === 'company') {
messages.getCompanyUnreadCount(req.session.uid, function(err, result) {
req.session.messageCount = result[0].unread;
next();
});
} else if(req.session.type === 'coder') {
messages.getCoderUnreadCount(req.session.uid, function(err, result) {
req.session.messageCount = result[0].unread;
next();
});
}
} else {
next()
}
});