Retrieving data from mongoDB using a field - node.js

I want to retrieve all the datas from my mongo db collection "Assets" whose "chapterName" is equal to the string sent through the url, How to get it?
app.get(`/api/assets/get_all/${chapterName}`, (req, res) => {
Assets.find({}, (err, assets) => {
if (err) return res.status(400).send(err);
res.status(200).send(assets);
});
});

the chapterName will be in params of request, req. let's say chaptername is present in mongoose schema.
app.get('/api/assets/get_all/:chapterName}', (req, res) => {
Assets.find({ chaptername: req.params.chapterName }, (err, assets) => {
if (err) return res.status(400).send(err);
res.status(200).send(assets);
});
});

Related

Editing Large Collection in MongoDB

I am trying to edit an entire collection in my MongoDB Database.
The collection is about 12k documents in size.
I was trying to edit the files from my angular controller
let promises = [];
array.forEach(each => {
promises.push(this.commonService.postObject('editObject', each));
});
forkJoin(promises).subscribe(data =>{})
My node function
module.exports.editObject = (model) =>{
return function (req, res, next) {
model.findOneAndUpdate({
'_id': req.body._id
}, req.body, {
upsert: true
}, function (err, doc) {
if (err) return res.send(500, {
error: err
});
return res.send(req.body);
});
};
}
But I get the error Message
ERR_INSUFFICIENT_RESOURCES
Is there a smarter way to do that?

Deleting orders works, deleting coffees doesn't. Identical functions

I have to build a CRUD in nodejs+express+mongodb and I have a function to delete orders, which is successfully deleting orders by a parameter, and a copy of this function adapted to "coffees" MongoDB collection.
The second returns undefined, or simply {}.
First I modified the collection and then different sources as arguments.
Here is server.js
// This code works.
app.delete('/orders/:coffee_id', (req, res) => {
db.collection('orders').findOneAndDelete({name: req.body.coffee_id}, (err, result) => {
if (err) return res.send(500, err)
res.json('Order deleted')
})
})
// Orders Collection. This means visiting localhost:3000/orders/Delta returns Order deleted
// Code not working as expected:
app.delete('/coffees/:id', (req, res) => {
db.collection('coffees').findOneAndDelete({'name': req.body.name}, (err, result) => {
console.log(res.body) // returns undefined.
if (err) return res.send(500, err)
res.json(req.body)
})
})
Coffees collection. Can't delete from this table. Postman DELETE to localhost:3000/coffees/Jamaica returns {} and console.log(res.body) returns undefined
Does anybody see something wrong? Please let me know if you require more code.
Thanks in advance.
A couple of things to note here.
1) Your routes are configured with path parameters, but you're trying to reference properties from req.body. I'm not sure how this is working in the first route, but I expect that it should not. You should be using req.params to access the path parameters.
app.delete('/orders/:coffee_id', (req, res) => {
db.collection('orders').findOneAndDelete({name: req.params.coffee_id}, (err, result) => {
...
})
})
2) In the second route you've declared a path parameter id, but you're attempting to access a property called name. This is where the implementation differs from the "working" route. It's not clear at face value if you want to use the ObjectId of document to perform deletions, or if you were planning using the name of the document.
Using the ObjectId:
app.delete('/coffees/:id', (req, res) => {
db.collection('coffees').findOneAndDelete({_id: req.params.id}, (err, result) => {
...
})
})
Using the name:
app.delete('/coffees/:name', (req, res) => {
db.collection('coffees').findOneAndDelete({name: req.params.name}, (err, result) => {
...
})
})
The takeaway here is that you must use the same value to reference the path param as the value declared in the path param.
/coffees/:id => req.params.id (not req.params.name)
Apparently I had to define a ObjectId like
var ObjectId = require('mongodb').ObjectID; //Include ObjectId
//then
app.delete('/coffees/:id', (req, res) => {
db.collection('coffees').findOneAndDelete({'_id': ObjectId(req.params.id)}, (err, result) => {
console.log(result)
if (err) return res.send(500, err)
res.json(result.body)
})
})

Express app.put / app.post outputs null values

I'm really new to node/express/mongoDB coding, and I have a slight problem with adding/updating values into mongoDB via node/express.
app.post('/', (req, res, next) => {
let data = {
first_value: req.body.first_value,
second_value: req.body.second_value,
};
dbase.collection("testDB").insertOne(data, (err, result) => {
if (err) {
console.log(err);
}
res.send('data added successfully');
});
});
app.put('/:id', (req, res, next) => {
var id = { _id: new ObjectID(req.params.id) };
dbase.collection("testDB").updateOne({ _id: id }, {
$set: {
first_value: req.body.first_value
second_value: req.body.second_value,
}
}, (err, result) => {
if (err) {
throw err;
}
res.send('data updated sucessfully');
});
});
app.put does not alter the values in DB, and app.post only adds "null" into every section of the new entry when I'm trying them with Postman. When I add new values with html form, the data is added correctly.
What is the problem with my code?
For app.post , can you provide me a screen shot of the way you are entering data and in which format e.g. , application/raw , application/x-www-form-urlencoded etc .
For app.put you need to correct the following things . The corrected code is as below ,
app.put('/:id', (req, res, next) => {
var id = { _id: new ObjectID(req.params.id) };
dbase.collection("testDB").updateOne( id , { // put "id" instead of "{ _id: id }"
$set: {
first_value: req.body.first_value
second_value: req.body.second_value,
}
}, (err, result) => {
if (err) {
throw err;
}
res.send('data updated sucessfully');
});
});
Hope you can get the point and this works for you .

item is not deleting from the database, the item should be the :item in the app.delete('/todo/:item') int the code below

app.delete('/todo/:item', (req, res) => {
console.log(req.params.item);
//here remove is not working as expected//
Todo.find({item: req.params.item}).remove((err, data) => {
if(err) throw err;
res.json(data);
});
});
You have to provide the remove method with a condition:
Todo.remove({ item: req.params.item }, (err, data) => {
if (err) { return res.status(500).json({ errorMessage: err });
res.status(200).json(data);
});
Models have a static remove method available for removing all documents matching conditions.
from Mongoose docs

GET request for specific id returning null

I'm attempting to build a simple CRUD application using express and mongodb. My GET request for all database entries is working and my POST request is working but I can't seem to figure out the problem with my GET request for individual entries.
Server.js GET request:
app.get('/api/:id', function (req, res) {
var id = req.params.id;
db.collection('api').findOne({_id: id}, (err, result) => {
if (err){
res.sendStatus(404);
return console.log(err);
}
res.redirect('/');
return console.log(result);
});
});
When I type 'url/api/593555074696601afa192d7f' which is an ID I know exists the console.log is returning null, I'm not sure if I'm doing something wrong?
You should pass ObjectID instance in the query.
let ObjectID = require("mongodb").ObjectID;
app.get('/api/:id', function (req, res) {
var id = req.params.id;
db.collection('api').findOne({_id: ObjectID(id)}, (err, result) => {
if (err){
res.sendStatus(404);
return console.log(err);
}
res.redirect('/');
return console.log(result);
});
});
Give Mongoose a try. It might be of help if your models get complex.

Resources