Sails.js - issues when trying to display model data - javascript

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
});
}
});
}

Related

get route showing null in response

I'm using TypeScript for making a GET request to get all members whose isCore is true. I've made several entries in the SQL database but it is showing null in res.json. Is the condition syntax is correct?
code:
router.get('/coreMem', async(req, res)=>{
try {
const core_member_details = await Member.findAll({
where:{
isCore: true
}
})
res.status(200).json(core_member_details);
}
catch (err) {
logger.error(`${err}`);
res.status(500).send('Internal Server/Database Error!');
}
});
I think that it, make sure that the Member model is correctly defined and that it is able to connect to the correct table in the database.
if not, a tip for you which is good debugging method:
To return all the records from the members table, you can use the findAll method without any conditions, like this:
router.get('/coreMem', async(req, res)=>{
try {
const all_member_details = await Member.findAll();
res.status(200).json(all_member_details);
},
catch (err) {
logger.error(${err});
res.status(500).send('Internal Server/Database Error!');
}
});

MongoNetworkError: connection establishment was cancelled

I'm trying to update a database using Mongoose, but I'm getting this Network error while running my node app.
const mongoose = require('mongoose')
mongoose.connect("mongodb://localhost:27017/fruitsDB")
const fruitsSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Why no Name?"]
},
rating: {
type: Number,
min: 1,
max: 10
},
review: String
});
const Fruit = mongoose.model("Fruit", fruitsSchema)
Fruit.find(function(err, fruits){
if(err){
console.log(err)
}
else{
mongoose.connection.close();
fruits.forEach(function(fruit){
console.log(fruit.name)
})
}
})
Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err){
if(err){
console.log(err)
}
else{
console.log("Successfully updated the document")
}
})
Error: Commnad line error while running the node app
MongoNetworkError: connection establishment was cancelled
at connectionFailureError
at CancellationToken.<anonymous>
at Object.onceWrapper (node:events:641:28)
at CancellationToken.emit (node:events:527:28)
at ConnectionPool.close
at Server.destroy
at destroyServer
at eachAsync
It's a simple Node app created using Mongoose.
Calling the find function last worked for me. I mean, like this -
Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err){
if(err){
console.log(err)
}
else{
console.log("Successfully updated the document")
}
})
Fruit.find(function(err, fruits){
if(err){
console.log(err)
}
else{
mongoose.connection.close();
fruits.forEach(function(fruit){
console.log(fruit.name)
})
}
})
Closing the connection should be at end which is the reason why the code is not getting properly executed.
I tried Calling the find function last but still getting the same error like this:
MongoNetworkError: connection establishment was cancelled
I don't know how to tackle this issue when it occurs in a running application but for now if you want to just insert the docs in collection then just comment the .find method completely and then run the application it will be inserted successfully and then comment the .updateOne method and uncomment the .find method by doing you will be successfully added the docs and could get the find result.
I did the same!
OR
I found out that for some reason .find method gets executed before .updateOne so the connection were being closed before the collection gets updated.
So, if we do this it works.
Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err) {
if (err) {
console.log(err)
} else {
Fruit.find(function(err, fruits) {
if (err) {
console.log(err)
} else {
mongoose.connection.close();
fruits.forEach(function(fruit) {
console.log(fruit.name)
})
}
});
console.log("Successfully updated the document")
}
})
You can't close the connection in the find method. You are not able to interact with the db after you closed the connection. Just put mongoose.connection.close() at the end.
Just Do something like this:
`People.insertMany([man1, man2, man3],
function (err) {
if (err) {
console.log(err);
} else {
console.log("Successfully saved all
models in the database");
mongoose.connection.close();
}
});`
Closing the connection inside insertmany worked for me
After reading some solutions the TL:DR is: the mongoose.disconnect();, it's the one causing problems, the connection is being terminated before you can update anything
You should be careful while using crud methods on database. Because those methods are asynchronous.
In your case the find method executed first and closed the database connection prior to updateOne method.
Solution: You can solve that by simply changing the logic in your code like embedding find method inside updateOne method or viseversa according to your need.(By embedding we are making a way to execute them in order)
Fruit.find(function(err, fruits) {
if (err) {
console.log(err)
} else {
fruits.forEach(function(fruit) {
console.log(fruit.name)
})
Fruit.updateOne({_id:"62b6a681eb136efde7ed17bc"}, {name: "Banana"}, function(err) {
if (err) {
console.log(err)
} else {
mongoose.connection.close();
console.log("Successfully updated the document")
}
})
}
})

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.

How to call delete from other class MEAN

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.

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