How to delete document from mongoDB collection using the document's ID? - javascript

I am trying to remove a document from a mongoDB collection by finding the document in the collection using an id. Below is a snippet of my code and it says that the note was successfully deleted but when I go back to where all the notes are displayed, the note that was supposedly deleted is still there.
router.post('/delete', function(req, res) {
notesCollection.remove(prevID, function(err, records){
if(err){
res.render("deleteFail.jade");
}
else{
res.render("deleteSuccess.jade");
}
});
});
Where prevID is the _id of the note currently trying to be deleted. Any help is greatly appreciated! Thanks

Are you using mongoose? I am pretty certain the first argument has to be a query object, e.g. { _id: prevId } and not just the id directly.

Related

Confusing error message using updateOne() function on a mongodb collection

To summarize, I have a mongodb database with a 'groupcollection' in it. One of the attributes is called 'deleted' and it has values either true or false. I want to update the value of 'deleted' for a specific document using 'groupname' as the query attribute. However, when I try the code below I receive the error "TypeError: collection.updateOne is not a function"
router.post('/deletegroup', function(req, res) {
var db = req.db;
var collection = db.get('groupcollection');
var filter = {"groupname" : req.body.groupname};
var updates = { $set: {"deleted" : true} };
collection.updateOne(filter, updates, function(err) {
if (err) {
// If it failed, return error
res.send("There was a problem deleting the group from the database.");
}
else {
// And forward to success page
res.redirect("grouplist");
}
});
});
I've read the documentation on updateOne() for Node.js from mongoDB and I can't seem to figure out the reason for the error. Also, I am still very new to javascript/nodejs/mongo so I would greatly appreciate more informative answers!
The solution I came up with was using unique IDs for each group and instead of using updateOne() just using update() and having the unique ID as the query to make sure that I don't modify groups with the same name

Node.js/mongoose - sub-document in a array won't delete/remove

So this is my first on-my-own node.js project after finishing up an online Bootcamp. Running into trouble removing a sub-doc in my array. Here's some code, I hope I provide enough info for someone to help me out.
models:
var productSchema = new mongoose.Schema({
name: String,
type: String,
location: String
});
var clientSchema = new mongoose.Schema({
name: String,
address: String,
contactinfo: String,
products:[]
});
And this is my post route that is adding the product to the client, which works great:
//Add New Product
app.post("/clients/:id/products", middleware.isLoggedIn, function(req, res){
Client.findById(req.params.id, function(err, client) {
if(err){
console.log(err);
req.flash('error', "We cannot find the Client!!!");
return res.redirect("/clients/" + req.params.id + "/products/new");
}
Product.create(req.body.product, function(err, product){
if(err){
req.flash('error', "There was an error adding the product to the user, try again");
} else{
client.products.push(product);
client.save();
req.flash('success', "You have added a New Product");
res.redirect('/clients/' + req.params.id +'/products/new');
}
});
});
});
My delete route is my problem child. It deletes the product, but I can't seem to get it out of the array at all. I did some research and tried the following:
client.products.find({_id:req.params.product_id}).remove()
client.products.id(req.params.product_id).remove()
client.products.pull({_id: req.params.product_id})
client.find({products:{_id: req.params.product_id}}).remove()
using client.save() right after each
I get errors or it deletes the client,
but never deletes the product from the array. Any help would be great or if there's a better way to do this, that would be great too. Tried for a week before turning for help, so open for feedback from skilled developers.
oh here is my last delete route, think I'm going to disable until I found a fix , so I can continue my project.
//Delete a Product
app.delete("/clients/:id/products/:product_id", middleware.isLoggedIn, function(req, res){
Product.findByIdAndRemove(req.params.product_id, function(err){
if(err){
console.log(err);
} else {
console.log("Should be deleted now!");
Client.findById(req.params.id, function(err, client) {
if(err){
console.log(err);
}
console.log(client.products.length);
client.find({products: {_id: req.params.product_id}}).remove();
client.save();
console.log(client.products.length);
res.redirect("/clients/");
});
}
});
});
The length I used to see if anything changed and it never did.
First, your method requires a objectID. Try like this and see if it works:
Product.findByIdAndRemove(ObjectId(req.params.product_id)
Nevermind, it seems that the issue here is my code. Instead of pushing a ref in my client schema for the products array I pushed the product info directly in the array. Then in my app in one area I'm accessing the data from the Product collection, but in another part of my app I'm accessing the same info from the client collection through the products array. Based on my training(Other course apps I created) it seems that the ref doesn't get remove it just can't refer to the collection since it's no longer in the collection.
Thank you Laurentiu & Federico for looking at this and providing some helpful information. sorry about any headaches this may have caused you.
Looked into documents and it won't delete. It deletes the content not the ID, so it stays in the MongoDB Database.
router.delete('/inventario/:_id', function(req, res){
Propiedades.findByIdAndDelete(req.params._id, function(err,){
if (err){
res.redirect('/inventario/');
} else {
res.redirect('/inventario/');
}
})
});

Error with get request for users

When using a get request for all the users in my database (see code below) i only get the "first" user in the database. If i instead try to use the "findOne"-method i get the same user as before no matter what i put in (the username doesn't even have to be in the db it still gives me the same user). I've been trying to understand why this isn't working but can't find any problems with the code. Could it be a problem with db settings or something similar? All help is appreciated!
In AuthController:
// Get all users
AuthController.allusers = function(req, res) {
User.find({}, function(err, users) {
}).then(function(users) {
res.json({users: users});
});
}
In routes:
// GET Routes.
router.get('/users', AuthController.allusers);
Since you are using Sequelizejs, you might want to do findAll.
AuthController.allusers = function(req, res) {
User.findAll().then(function (users) {
res.send({users: users});
}
}
According to the docs:
find - Search for one specific element in the database
findAll - Search for multiple elements in the database

Mongo find Document after Insert

i use sails js 0.12.14 with mongodb. if i try to get a document after insert the document the document is empty
Products.create(product).exec(function(err, createdProduct) {
Products.find({_id : createdProduct.id}).exec(function(err, foundProductAfterCreate) {
console.log(foundProductAfterCreate);
})});
Can anybody explain why the document is not available?
Update:
This is the correct code for me...
Products.create(product).exec(function(err, createdProduct) {
Products.find({_id : createdProduct[0].id}).exec(function(err, foundProductAfterCreate) {
console.log(foundProductAfterCreate);
})});
The doc you are querying for is literally the same one you already have
Products.create(product).exec(function(err, createdProduct) {
// handle the error...
console.log(createdProduct); // the full record
});
createdProduct is exactly the same object you would get if you queried by id.
If you do ever need to query by id, sails does a fairly comprehensive switch from _id which is the mongo standard, to id with no underscore. You would do that like this:
Products.findOne({id: createdProduct[0].id}).exec(function(err, foundAgain) { // etc
...no underscores anywhere unless you use .native for more basic mongo query access.

Node.js delete query for "mongodb"

I have been trying to understand why this delete query doesn't work for days, and I just can't see the problem.
I've tried many different delete queries like deleteOne, findOneAndDelete, deleteMany but none of them worked.
I use the "mongodb" client for node.js
mongo.connect(serverAddress, (err, db) => {
//(db connection is ok, server can find and create documents)
var doc = db.collection('myCollection'),
docToDelete = "575807172154b7a019ebf6db";
//I can see the same document id on my database
doc.deleteOne({"_id":docToDelete}, (err, results) => {
console.log(`Request success : ${results.result.ok}, documents deleted : ${results.result.n}`);
//Request success : 1, documents deleted : 0, the document is still on my database
});
}
//the doc var is the same I use to add/find documents (and it works).
When I use the same query in softwares like MongoClient, it works.
I have tried many solutions posted on this site and sorry if the error is too obvious but I'm totaly lost.
Thanks for your help.
The problem is that _id in the database is of type ObjectId, but in your query it's a String. You have to be strict about that, otherwise the query won't match the document.
Try this:
const mongodb = require('mongodb');
...
doc.deleteOne({ _id : mongodb.ObjectId(docToDelete) }, (err, results) => {
...
});

Categories