Query multiple mongodb collections in node app using Mongoose async - node.js

In my node.js app I want to query multiple mongodb collections in a series using mongoose with the async plugin based on result from the first callback in the series.
So far I have this working code but I'm sure there is a better way of doing it async:
router.route('/project/:projectId')
.get(function(req, res) {
var getProjectDetails = function(cb) {
models.Project.findById(req.params.projectId, function(err, project) {
if(err)
res.send(err);
models.Media.find({'project_code' : project.code }, function(err, media) {
cb(null, {'project' : project, 'media': media})
});
})
}
async.parallel([getProjectDetails], function(err, result) {
res.render('details', {data: result});
});
});
As you can see I want to find all entries from the Media collection where project_code equals code from Project collection.
How can I acvhieve this without nesting my mongoose-querys?

Why do you need async in this? I hope this will work.
router.route('/project/:projectId')
.get(function(req, res) {
models.Project.findById(req.params.projectId, function(err, project) {
if(err)
return res.send(err);
models.Media.find({'project_code' : project.code }, function(err, media) {
if(err)
return res.send(err);
return res.render('details', {data: {'project' : project, 'media': media}});
});
});
});

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?

How to delete a particular row in Node.js and express

How can I delete data from a list in Node.js, using express and ejs view? I have tried, but it's not working. I am using mongodb.
Here is what I have done so far but it's not working.
router.post('/delete', function(req, res, next) {
var id = req.body.id;
mongodb.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('profile').deleteOne({ "_id": objectId(id) }, function(err, result) {
console.log('Item deleted');
db.close();
});
});
res.redirect('/userlist');
});
and ejs (view) code is:
<td>Delete</td>
below code is works but when I press Delete, it deletes all the row. Here I used get intead of post
router.get('/delete', function(req, res, next) {
mongodb.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('profile').deleteOne(function(err, result) {
console.log('Item deleted');
db.close();
});
});
res.redirect('/userlist');
});
If you want to use a get request, it can be done like this:
router.get('/delete/:id', function(req, res, next) {
var id = req.params.id;
mongodb.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('profile').deleteOne({ "_id": objectId(id) }, function(err, result) {
console.log('Item deleted');
db.close();
});
});
res.redirect('/userlist');
});
Now you need to request something like this:
<td>Delete</td>

Sails js afterCreate

I'm using models in sails and I wrote an afterCreate which just populateAll properties of my new record.
My problem is that when I wrote :
Model.create(values, function(err, record) {
console.log(record)
}
the code for after create is :
function afterCreate (object, next) {
Model.findOne(id: obj.id)
.populateAll()
.exec(function(err, populated) {
next(null, populated)
}
The logged record is not populated.
Do you have an idea why I don't get the populated record ?
Thank's !
To resolve this problem I just created an function in the model called createAndPopulate()
Like that :
createAndPopulate: functuion(values, next) {
Model.create(values, function(err, record) {
if (err) {
return next(err);
}
Model
.findOne({
id: record.id
})
.populateAll()
.exec(function(err, populated) {
if (err) {
return next(err);
}
return next(null, populated);
});
});
}
And it's work !
Hope it's will help.
I think you just have to name obj to object

NodeJS / Mongoose Filter JSON

I am building a JSON API with ExpressJS, NodeJS and Mongoose:
Input -> id:
app.get('/folder/:id', function (req, res){
return Cars.find({reference: req.params.id}, function (err, product) {
if (!err) {
console.log(product);
return res.send(product);
} else {
return console.log(err);
}
});
});
It shows well the JSON:
[{"_id":"B443U433","date":"2014-08-12","reference":"azerty","file":"087601.png","
....:.
{"_id":"HGF6789","date":"2013-09-11","reference":"azerty","file":"5678.pnf","
...
I just want to display the _id in the JSON, so it is good when I have lots of data.
How I can do that? Something like a filter?
You can chain calls to select and lean to retrieve just the fields you want from the docs you're querying:
app.get('/folder/:id', function (req, res){
return Cars.find({reference: req.params.id}).select('_id').lean().exec(
function (err, product) {
if (!err) {
console.log(product);
return res.send(product);
} else {
return console.log(err);
}
});
});
You would have to iterate over your "products" object to obtain the ids
Something like this:
(Disclaimer: I haven't tested this)
app.get('/folder/:id', function (req, res){
return Cars.find({reference: req.params.id}, function (err, product) {
if (!err) {
console.log(product);
var ids = new Array();
for(var i = 0; i < product.length; i++){
ids.push(product[i]._id);
}
return res.send(JSON.stringify(ids));
} else {
return console.log(err);
}
});
});
--Edit
Also, "products" may already be a JSON string. You may want to parse it before looping.
product = JSON.parse(product);
Other answers are true but I think it's better to limit data in mongoose like this :(it's same as mongo shell commands)
app.get('/folder/:id', function (req, res){
Cars.find({reference: req.params.id} ,{ _id : true } ,function (err, product) {
if (!err) {
console.log(product);
} else {
console.log(err);
}
});
});

After form submission, new data does not appear without page reload

In my ExpressJS app I have two routes to the same location, one for 'get' and one for 'post'.
On the 'get' page it dumps all the documents from my MongoDB collection, via MongooseJS, followed by a form to add a new record to the collection.
On the 'post' page it takes in the form data and adds it to the collection, and then displays the same page you see via 'get'.
It works, but after the form is submitted the new record doesn't appear unless I reload the page. I put the code that renders the page at the very bottom, below the part that adds the data to the collection so in my mind that should work but it doesn't.
exports.index = function(req, res){
Server.find({},
function(err, docs) {
if (!err){
res.render('servers', { title: 'verify', results: docs});
}
else { console.log(err);}
}
);
}
exports.add = function(req, res){
newServer = new Server({
name: req.body.name,
os: req.body.os,
osVersion: req.body.osVersion
});
newServer.save(function (err) {
if (err) {
console.log(err);
}
});
Server.find({},
function(err, docs) {
if (!err){
res.render('servers', { title: 'verify', results: docs});
}
else { console.log(err);}
}
);
}
Ok, I seem to make this mistake over an over again with callbacks. I fixed the problem.
exports.add = function(req, res){
newServer = new Server({
name: req.body.name,
os: req.body.os,
osVersion: req.body.osVersion
});
newServer.save(function (err) {
if (err) {
console.log(err);
} else {
Server.find({},
function(err, docs) {
if (!err){
res.render('servers', { title: 'verify', results: docs});
}
else { console.log(err);}
}
);
}
});
}
Yes, those DB queries are async, so callbacks will solve this issue. However, you should look into using promises. Mongoose returns promises by default or you could import your library of choice. They will come in handy when dealing with nested callbacks and queries and also Error handling.

Resources