Nodejs Mongoose Saving model undefined is not a function - javascript

I work with Nodejs Express routes and Mongoose to persist data.
I did the core routes CRUD operations with no problem. However, when I try to perform some operations on one of the fields of the Model and then try to save the Model with model.save it says about .save() method: "undefined is not a function"
So, here's the code.
The snippet number (1) works just fine:
router.put('/:myId', function (req, res, next) {
var ourUpdateData = req.body;
Model.findOne({myId: req.params.myId.toString()}, function (err, foundModel) {
if (err) throw err;
if (ourUpdateData.fieldA) foundModel.fieldA = ourUpdateData.fieldA;
if (ourUpdateData.fieldB) foundModel.fieldB = ourUpdateData.fieldB;
if (ourUpdateData.fieldC) foundModel.fieldC = ourUpdateData.fieldC;
if (ourUpdateData.fieldD) foundModel.fieldD = ourUpdateData.fieldD;
if (typeof ourUpdateData.fieldArray === "object") ourUpdateData.fieldArray = ourUpdateData.fieldArray;
foundModel.save(function (err, updatedModel) {
if (err) throw err;
res.send(updatedmodel);
});
});
});
So the Model has 6 fields: fieldA,..B,..C,..D, myId to identify as index and one field is Array of some values fieldArray. The example above saves the Model, works fine.
However if I now try to do something with array field fieldArray and then save the Model it throws me "undefined is not a function" when I use model.save() .
So the snippet (2) is the code that produces this error:
router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
var myId = req.params.myId;
var addThisToFieldArray = req.params.addThisToFieldArray;
Model.find({myId: myId}, function (err, model) {
if (err) throw err;
var fieldArray = model.fieldArray;
fieldArray.push("New thing to FieldArray");
var newFieldArray = fieldArray;
if (typeof newFieldArray === "object") model.fieldArray = newFieldArray;
model.save(function (err, updatedModel){
if (err) throw err;
res.send(updatedModel);
});
});
});
So that thing above throws "undefined is not a function" on using model.save(.. )
I also tried second variant of the snippet (2), let's call it snippet (3), incorporating the .exec() Also doesn't work, throws the same "undefined is not a function" on model.save(.. )
So the snippet (3) is this:
router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
var myId = req.params.myId;
var addThisToFieldArray = req.params.addThisToFieldArray;
Model.find({myId: myId}).exec(function (err, model) {
if (err) throw err;
var fieldArray = model.fieldArray;
fieldArray.push("New thing to FieldArray");
var newFieldArray = fieldArray;
if (typeof newFieldArray === "object") model.fieldArray = newFieldArray;
model.save(function (err, updatedModel){
if (err) throw err;
res.send(updatedModel);
});
});
});
I'll be greatful for any inputs and suggestions!
Ansering to the attempt of Willson:
Yeah, I know when I call model.find(.. it gives array, if I call model.findOne(.. it gives one object json
I tried to simplify my example and in my version I actualy did use the:
"model[0].fieldArray = newFieldArray" to get the thing from Array fist (the array itself) and then assign to the new value.
The problem still persists, it gives me on model.save(.. "undefined is not a function " )
The current code is:
router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
var myId = req.params.myId;
var addThisToFieldArray = req.params.addThisToFieldArray;
Model.find({myId: myId}).exec(function (err, model) {
if (err) throw err;
var fieldArray = model[0].fieldArray;
fieldArray.push("New thing to FieldArray");
var newFieldArray = fieldArray;
if (typeof newFieldArray === "object") model[0].fieldArray = newFieldArray;
model.save(function (err, updatedModel){
if (err) throw err;
res.send(updatedModel);
});
});
});
This snippet (4) above gives on model.save(.. "undefined is not a function"

When you use in Mongoose the find method, it will return an array since it could discover one or many documents, so in your example you are querying to one specific element by its id, you should grab the first element on the returned array:
Model.find({myId: myId}).exec(function (err, documents) {
var model = documents[0];
if (err) throw err;
var fieldArray = model[0].fieldArray;
Here is an example:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost:27017/java-jedi');
var HackerSchema = new Schema({
name: String,
languages: [String]
});
var Hacker = mongoose.model('Hacker', HackerSchema);
// instantiating the model.
var oneHacker = new Hacker();
oneHacker.name = 'Richard Stallman';
oneHacker.save(function(err) {
if (err) throw err;
// finding the document intentionally for this example
Hacker.find({_id: oneHacker._id}, function(err, hackers) {
var hacker = hackers[0];
// modifying the document and updating it.
hacker.languages.push('Lisp');
hacker.save(function(err) {
if (err) throw err;
console.log(hacker);
});
});
});

OK guys!
I want to thank Wilson Balderrama, because he basically pointed to the right direction.
The code works! But let me clearify a bit.
Hacker.find({_id: oneHacker._id}, function(err, hackers) {
var hacker = hackers[0];
// modifying the document and updating it.
hacker.languages.push('Lisp');
hacker.save(function(err) {
if (err) throw err;
console.log(hacker);
});
});
So basically since the Model.find(.. returns an array
when we save we have to grab the thing from array before saving.
So corrected and final working version of my example will be:
router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
var myId = req.params.myId;
var addThisToFieldArray = req.params.addThisToFieldArray;
Model.find({myId: myId}).exec(function (err, model) {
if (err) throw err;
var fieldArray = model[0].fieldArray;
fieldArray.push("New thing to FieldArray");
var newFieldArray = fieldArray;
if (typeof newFieldArray === "object") model[0].fieldArray = newFieldArray;
model[0].save(function (err, updatedModel){
if (err) throw err;
res.send(updatedModel);
});
});
});
Or we can use just Model.findOne(.. to avoid confusing ourselves with this arry return
In this case we grab directly:
router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
var myId = req.params.myId;
var addThisToFieldArray = req.params.addThisToFieldArray;
Model.findOne({myId: myId}).exec(function (err, model) {
if (err) throw err;
var fieldArray = model.fieldArray;
fieldArray.push("New thing to FieldArray");
var newFieldArray = fieldArray;
if (typeof newFieldArray === "object") model.fieldArray = newFieldArray;
model.save(function (err, updatedModel){
if (err) throw err;
res.send(updatedModel);
});
});
});
So in second case model[0].save(... becomes model.save(... direct grabbing and saving.
Thank you Wilson Balderrama again!!

Related

Connection to Mongodb through Node.js

Hii Everyone
In my code, There is an API that works fine.
And I'm trying to connect to MongoDB from Node for the sake of inserting the data from the API.
As you can see, I get this error -
"message": "Uncaught SyntaxError: Unexpected identifier",
it looks like there is a problem with MongoClient.
I looked at the answers on this site about those topics and no one solves my problem.
Thanks for any help!
let http = require('http');
let weatherKey = process.env.weatherKey;
// console.log(weatherKey);
function getData(cb) {
http.get(`http://api.openweathermap.org/data/2.5/weather?q=israel&appid=${weatherKey}`, res => {
let data = ""
res.on('data', string => {
data += string
})
res.on('end', () => {
let obj = JSON.parse(data)
cb(obj);
})
}).on("error", error => {
cb(error);
})
}
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
function connectToMongo(data)
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("weather-db");
dbo.collection("node").insertOne(data, err => {
if (err) throw err;
console.log("documents inserted");
db.close();
});
});
getData(connectToMongo);
Your function is missing { after (data)
You were missing {} in your code.
let http = require('http');
let weatherKey = process.env.weatherKey;
function getData(cb) {
http.get(`http://api.openweathermap.org/data/2.5/weather?q=israel&appid=${weatherKey}`, res => {
let data = ""
res.on('data', string => {
data += string
})
res.on('end', () => {
let obj = JSON.parse(data)
cb(obj);
})
}).on("error", error => {
cb(error);
})
}
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
function connectToMongo(data){
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("weather-db");
dbo.collection("node").insertOne(data, err => {
if (err) throw err;
console.log("documents inserted");
db.close();
});
});
}
getData(connectToMongo);

Can you get node js to send an array not a string

I want the code to return a 2d array of the results.
E.g.
clothes = [[1,"name","desc"],[2,"name2","desc2"]]
can you make res send a list or do you have to make a list once you have returned it?
app.get('/post', (req, res) => {
con.connect(function(err) {
if (err) throw err;
var query = "SELECT * FROM products"
con.query(query, function (err, results, fields) {
if (err) throw err;
var clothes = [];
Object.keys(results).forEach(function(key) {
let r = []
var row = results[key];
r.push(row.ID);
r.push(row.name);
r.push(row.link);
r.push(row.imageLink);
r.push(row.type);
r.push(row.colour);
r.push(row.price);
r.push(row.brand);
clothes.push(r);
});
res.send(clothes);
});
});
});
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
clothes = this.response;
document.getElementById("demo").innerHTML = clothes;
};
xhttp.open("GET", "http://localhost:3000/post", true);
xhttp.send();
Yes of course.
Check out the official NodeJS documentation
Example:
app.get('/post', (req, res) => {
con.connect(function(err) {
if (err) throw err;
var query = "SELECT * FROM products"
con.query(query, function (err, results, fields) {
if (err) throw err;
var clothes = [];
...
// Better set the header so the client knows what to expect; safari requires this
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(clothes));
});
});
});
You seem to be using the expresjs framework
Here you have a convenience method to do the above:
...
con.query(query, function (err, results, fields) {
if (err) throw err;
var clothes = [];
res.json(clothes);
});
...
Read the response on the client side
This is a good answer on how to do this.
In short: It is recommended to use the new fetch() method on client side.
fetch("http://localhost:3000/post")
.then(function(response) {
return response.json();
})
.then(function(clothes) {
document.getElementById("demo").innerHTML = clothes;
});

why mongodb in node express cannot set result to outside variable

So this question might be a javascript concept question. but I cannot figure out why
I retrieve data from mongodb however, I cannot define _res variable to become the result.
console.log(_res) will return undefined.
Does anyone know why? and how to make it work as it should be?
app.route('/').get(function(req,res){
let _res;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vm");
var query = {};
dbo.collection("vm").find(query).toArray( function(err, result) {
if (err) throw err;
var vmData = JSON.stringify (result)
_res = vmData
db.close();
res.render('index.ejs', {
vmData: vmData
});
});
});
console.log(_res)
});
Mongodb query is an asynchronous operation. The console statement is executed before the query has been processed.
You define _res outside which is undefined outside, so the same value is consoled outside.
app.route('/').get(function(req,res){
let _res;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vm");
var query = {};
dbo.collection("vm")
.find(query)
.toArray((err, result){
if (err) throw err;
var vmData = JSON.stringify (result)
_res = vmData
db.close();
console.log('Inside', _res) // <---Should give you correct result
res.render('index.ejs', {
vmData: vmData
});
});
});
console.log('Outside', _res);
});
The code is being executed asynchronously due to which when the console.log is executed the _res is undefined.
Try to execute your logic when the asyn methods are being executed.
app.route('/').get(function(req,res){
let _res;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vm");
var query = {};
dbo.collection("vm").find(query).toArray( function(err, result) {
if (err) throw err;
var vmData = JSON.stringify (result)
_res = vmData;
console.log(_res);
db.close();
res.render('index.ejs', {
vmData: vmData
});
});
});
});

list folder with node.js

I'm beginner with node.js and I have a problem. I want to display the filename and last modification date in a list with a view ejs.
But, my problem is to pass the variable to my view, I want to fill in an arraylist with filename and one with date but nothing appears..
here is the code :
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/html');
var filenameArray = [];
var datefileArray = [];
fs.readdir('./PDF/', function (err, files) {
if (err) {
throw err;
}
files.forEach(function (file) {
fs.stat('./PDF/'+file, function (err, stats) {
if (err) {
throw err;
}
// Fill in the array with filename and last date modification
filenameArray.push(file);
datefileArray.push(stats.mtime);
});
});
});
filenameArray.push("test");
datefileArray.push("pouet");
res.render('files.ejs', { filename: filenameArray, dateModification: datefileArray, index: filenameArray.length });
});
and here is my view :
<p> <%= filename.length %></p>
<ul><%
for(var i = 0 ; i <= index; i++) {
%>
<li><%= filename[i] + " - " + dateModification[i] %></li>
<% } %></ul>
I have only the test item in my array..
Thank you.
Remember: node.js is asynchronous, so when you call render, the fs.readdir and the fs.stat inside it have not returned yet.
You can use the async module to help you with that:
var async = require('async');
app.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/html');
var filenameArray = [];
var datefileArray = [];
fs.readdir('./PDF/', function (err, files) {
if (err) {
throw err;
}
async.each(files, function (file, callback) {
fs.stat('./PDF/'+file, function (err, stats) {
if (err) {
throw err;
}
// Fill in the array with filename and last date modification
filenameArray.push(file);
datefileArray.push(stats.mtime);
callback();
});
}, function (error) {
if (error) return res.status(500).end();
res.render('files.ejs', { filename: filenameArray, dateModification: datefileArray, index: filenameArray.length });
});
});
});
The each function will execute the iterator callback for each item in the array, and at the end, when all iterator functions have finished (or an error occurs), it calls the last callback.

Node.js npm mssql function returning undefined

I am using mssql with node.js to connect to an sql server db. I am trying to reduce code by wrapping the connection code in a function with one query parameter. When I call the function from with in a router.get function, it returns undefined.
Any help would be much appreciated.
function sqlCall(query) {
var connection = new sql.Connection(config, function(err) {
if (err) {
console.log("error1");
return;
}
var request = new sql.Request(connection); // or: var request = connection.request();
request.query(query, function(err, recordset) {
if (err) {
console.log("error2");
return;
}
return (recordset);
});
});
}
router code
router.get('/', function(req, res) {
var queryString = "select * from .....";
res.json(sqlCall(queryString));
//sqlCall(queryString)
});
You are trying to treat the sqlCall as a synchronous function with a return value, while the request.query function on the opposite is an asynchronous function, expecting a callback.
Since Node.js uses non blocking IO and callback structures for flow control, using an asynchronous structure based around callbacks is the way to go. In your case this could look like this:
router.get('/', function(req, res) {
var queryString = "selec * from .....";
sqlCall(queryString, function(err, data) {
if (typeof err !== "undefined" && err !== null) {
res.status(500).send({
error: err
});
return;
}
res.json(data);
});
});
with your other component looking like this:
function sqlCall(query, cb) {
var connection = new sql.Connection(config, function(err) {
if (typeof err !== "undefined" && err !== null) {
cb( err );
return
}
var request = new sql.Request(connection); // or: var request = connection.request();
request.query(query, function(err, recordset) {
cb( err, recordset );
});
});
}

Categories

Resources