Deleting / removing with Mongoose with multiple parameters - javascript

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]

Related

FS write file is breaking my json, how to correctly update just one key?

I have a simple json object like so.
{
"gymData": {
"previousWorkouts": [
],
"exercises": [
]
}
}
both of the arrays above, are full of objects. I have 2 end points /workouts and /exercises.
my backend is just a simple express server with custom end points. when I add a new workout in the frontend and click submit, the /workouts endpoint behaves correctly.
however, I'm getting some issue when it's not updating the json correctly and resulting in a json error.
this is my node endpoint code
app.post("/exercises", function(req, res) {
fs.readFile('db.json', 'utf8', function (err, data) {
if (err) throw err;
let databaseData = JSON.parse(data);
const workoutExercises = req.body.workoutExercises.workouts
workoutExercises.forEach(exercise => {
const filteredExerciseDatabase = databaseData.gymData.exercises.filter(ex => ex.name === exercise.name)
filteredExerciseDatabase[0].previousWeights.push({date: req.body.date, weight: exercise.weight})
})
const updatedData = JSON.stringify(databaseData)
console.log(updatedData)
fs.writeFile('db.json', updatedData, 'utf8', function(err, data) {
if (err) throw err;
res.status(200).send("Basket was updated");
});
});
})
instead of writing the whole file again. I was wondering if I can just update the specific object key that I need too?
also, for reference, the error seems to be appending extra stuff onto the json object, so it's breaking. but in this line: console.log(updatedData) when I copy that logged data into a json validator, it is valid. so I'm confused as to why it's not writing the correct thing :/

Use the Node.js + PostgreSQL to get by id

I am trying to write an application with Node.js & PostgreSQL, currently I faced a problem in get by id, below is my code
app.get('/monsters/:id', (request, response, next) => {
const { id } = req.params;
pool.query('select * from monsters where id = $1', [id], (err, res) => {
if (err) {
return next(err);
}else {
response.json(res.rows);
}
});
});
it supposed to get the id I typed and return the value I stored in database with a table name called monster, however it just kept returning a blank object {}, I found the problem may because of the $1 part since my atom seemed not able to recognize $, what can I do to fix this problem or is there other way to write this instruction? Thank you!

MongoDB insert without duplicates

Right now I am running mongodb and I just realized, I am inserting into collections and I am not sure if I am preventing duplicates. Here is how I am inserting:
function insertCompanies(companyID, companyURL, companyAppID) {
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
} else {
console.log("We are connected");
}
var collection = db.collection('Companies');
var company = {
"companyProfileID": companyID,
"url": companyURL,
"appID": companyAppID
};
collection.insert(company, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
db.close();
});
}
I am using NodeJS. When a user calls the insertCompanies method, if the company already exists (via companyID or URL), it seems like the collection allows duplicates.
Is there a different insert function that prevents duplicates? I looked around and could not find a straight forward solution tailored to me.
Instead of db.insert() you should use db.update() and specify $upsert: true.
https://docs.mongodb.com/v3.2/reference/method/db.collection.update/
The answer is not to insert, instead use update. The update() method either modifies the fields in existing documents or replaces an existing document entirely.

Delete an object from an Elasticsearch response array

I'm trying to delete and object from my Elasticsearch result query, but this object persist whatever I do:
Here is my code :
exports.searchUserByKeyWord = (req, res) => {
User.search(byKeyWordQuery(req), geoDistance(), (err, users) => {
if (err) requestError(res, err)
let result = []
for(let user of users.hits.hits) {
delete user.address.full
result.push(user)
}
sendJsonResponse(res, 200, result)
})
}
Like you can see I'm using delete but it doesn't work, what I can't understand here is the fact that when I replace sendJsonResponse(res, 200, result) with
sendJsonResponse(res, 200, result[0].address.full) I found out that this address got successfully deleted, but when I test my API with Postman without adding result[0].address.full the address full field is still there ...
are you reindexing your elasticsearch data after you delete? the indexed record may persist even though you have removed the document from disk
more on this can be read #
https://www.elastic.co/guide/en/elasticsearch/guide/current/update-doc.html

Undefined error in MEAN CRUD

{ 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).

Categories