array schema store empty values - arrays

I want store values in mongodb using node controller but it will store an empty array inside mongodb
1).This is node controller using to accept the req parameter
this.childQuestionId = function(req, res, next){
try{
var userObj = {
'child.quiz.questionId' : req.params.questionId,
'child.quiz.score' : req.params.score,
//'child.quiz.time' : req.params.time
'child.quiz.time' : new Date().toISOString()
};
var childupdate = new childQuiz(userObj);
childupdate.save(function(err,data){
if(err) return next(err);
console.log("Data saved successfully");
res.send(data);
});
}catch(err){
console.log('Error While Saving the result ' +err);
return next(err);
}
}
2).This is mongodb schema using to store the value. Here i am using array quiz schema to store values is array
child:{
quiz:[
{
/*questionId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'commonquestions'
},*/
questionId:{type:String},
score:{type:Number},
time:{type:String}
}
]
}
3).This is my json result sending values using postman
{
"__v": 0,
"_id": "57a43ec68d90b13a7b84c58f",
"child": {
"quiz": []
}
}

MongoDB save() function accepts 2 parameters, document and data, but in your code, you use a callback function. Should you check it out?
https://docs.mongodb.com/manual/reference/method/db.collection.save/#db.collection.save

Try with this code in your controller
this.childQuestionId = function(req, res, next){
try{
var userObj = {
'questionId' : req.params.questionId,
'score' : req.params.score,
//'time' : req.params.time
'time' : new Date().toISOString()
};
var childupdate = new childQuiz();
childupdate.quiz.push(userObj);
childupdate.save(function(err){
if(err) return next(err);
console.log("Data saved successfully");
res.send(childupdate);
});
}catch(err){
console.log('Error While Saving the result ' +err);
return next(err);
}
}

Related

throw new ERR_INVALID_ARG_TYPE('chunk',['string','Buffer'],chunk);TypeError[ERR_INVALID_ARG_TYPE]:The "chunk" arg must be type string or Buffer

I am trying to get the contents of a .json file using a node js service into an angularjs method. But am getting following error:
_http_outgoing.js:700
throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object
at ServerResponse.end (_http_outgoing.js:700:13)
here are the corresponding code fragments...
angular controller: the commented lines are all of those which i have tried and failed with.
var currentProcess = "process_1cA";
$scope.storestats = [];
var resAss = $resource('/procs/getstorestats');
var stats = resAss.get({
process: currentProcess,
date: date.getFullYear() + "" + m + "" + d
});
stats.$promise.then(function(response) {
if (response != undefined) {
// var r = JSON.parse(response);
//$scope.storestats.push(r);
//$scope.storestats.push(r);
//var r = JSON.parse(response);
$scope.storestats.push(response);
//angular.forEach(r, function(value, key) {
// $scope.storestats.push({key : value});
//});
}
});
NODEJs service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.end(msgs1);
});
}
catch (err) {
res.end(err.toString());
}});
P.S: The commented out lines are those which i have tried out with and failed. Also, the commented lines in the node service code snippet, give no error, and when logged show it correctly, but the data when in response of the controllers is blank.
I'm guessing a bit here, but I think you just need to change res.end() to res.send() in your Node code. The "end" method is used when you are streaming chunks of data and then you call end() when you're all done. The "send" method is for sending a response in one go and letting Node handle the streaming.
Also, be sure you are sending a string back!
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.send(msgs2); // NOTE THE CHANGE to `msg2` (the string version)
});
}
catch (err) {
res.send(err.toString()); // NOTE THE CHANGE
}
});
I had a similar error. It was because I was passing process.pid to res.end(). It worked when I changed process.pid to string
res.end(process.pid.toString());
Figured it out. 2 small changes were needed.. One in the controller, which was to use a "$resource.query" instead of "$resource.get". And in the service, as #jakarella said, had to use the stringified part in the .end();
Controller:
var resAss = $resource('/procs/getstorestats');
var stats = resAss.query({process: currentProcess, date: date.getFullYear() + "" + m + "" + d});
stats.$promise.then(function (response) {
$scope.storestats.push(response);
}
Node Service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
var msgs2 = JSON.stringify(msgs1);
console.log(msgs2);
res.end(msgs2);
});
}
If you are using 'request-promise' library set the json
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
})
.catch(function (err) {
});
Thank you user6184932, it work
try {
await insertNewDocument(fileNameDB, taskId);
res.end(process.pid.toString());
} catch (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
in mysql2 the reason for the error is the sql word , sql is a query :
const sql = select * from tableName
pool.executeQuery({
sql,
name: 'Error list for given SRC ID',
values: [],
errorMsg: 'Error occurred on fetching '
})
.then(data => {
res.status(200).json({ data })
})
.catch(err => {
console.log('\n \n == db , icorp fetching erro ====> : ', err.message, '\n \n')
})
I got the error using Node v12 (12.14.1).
Uncaught TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number
Sample code for context.
const { Readable } = require('stream')
Readable.from(Buffer.from(base64content, 'base64'))
.pipe( ... )
Solution (for my case), was upgrading to Node v14 (14.17.3). e.g.
nvm use 14
nvm

Instead of saving inside array, data is getting stored inside new record [duplicate]

This question already has answers here:
Push items into mongo array via mongoose
(11 answers)
Closed 5 years ago.
I am uploading images using MEAN stack and Multer module.
I am able to retrieve images from the angular, and can even post image-paths to Mongoose collection.
The problem is I am expecting an array of images but while posting to mongoose, it's storing each image as a new record.
Image schema
var imageSchema=new Schema({
productId:{type: String,required: false},
imagePaths: [{type: String, required: false}]
});
POST API
router.post('/upload', upload.any(), function(req , res){
console.log('Executing Upload API..');
console.log(req.body);
console.log(req.files);
var images = req.files;
req.files.forEach(function(file){
var filename = (new Date()).valueOf() + '-' + file.originalname;
fs.rename(file.path,'public/images/'+ filename, function(err){
// if (err) throw err;
//Save to mongoose
var image = new Image({
productId: 1007,
imagePaths: filename
});
image.save(function(err, result){
if(err) throw err;
res.json(result);
});
console.log('FileName :' + filename);
});
});
});
Collection saved
If I post 2 images, it's getting stored as shown below, but I want both the images to be sotred in same record, i.e inside imagePaths:.
**
{
"_id" : ObjectId("59abab004783d90bccb4a723"),
"productId" : "1007",
"imagePaths" : [
"1504422656691-Screenshot (4).png"
],
"__v" : 0
}
{
"_id" : ObjectId("59abab004783d90bccb4a724"),
"productId" : "1007",
"imagePaths" : [
"1504422656691-Screenshot (3).png"
],
"__v" : 0
}
**
Please help.
In your forEach, you are creating new record for every file with new Image, rather what you should be doing is create an array of all the filename and make the record once. Maybe this piece of code will help you.
router.post('/upload', upload.any(), function(req , res){
console.log('Executing Upload API..');
console.log(req.body);
console.log(req.files);
var images = req.files;
const filePromises = req.files.map(function(file){
var filename = (new Date()).valueOf() + '-' + file.originalname;
console.log('FileName :' + filename);
return new Promise(function(resolve, reject) {
fs.rename(file.path,'public/images/'+ filename, function(err) {
if (err) return reject(err);
return resolve(filename);
});
});
});
Promise.all(filePromises)
.then( fileNames => {
var image = new Image({
productId: 1007,
imagePaths: fileNames
});
image.save(function(err, result){
if(err) throw err;
res.json(result);
});
})
});
In this I have created the array of promises which will contain filename, and then resolving all of them using Promise.all to finally get the resolved array of filename, which then I can simply pass to create a new record.

Nodejs S3 Delete Multiple Objects Error

I am trying to bulk delete my s3 objects that are associated with one specific blog record in my database, but I'm getting hung up on how to pass the array to my params object to be used in the s3.deleteObjects method, but I'm held up on this error: Check with error message InvalidParameterType: Expected params.Delete.Objects[0].Key to be a string. I feel like it could be related to not having a loop at some point in the process or maybe the format of the values being passed to my s3File array.
Here is the my routing:
.delete(function(req, res){
models.File.findAll({
where: {
blogId: blog.blogId
}
}).then(function(file){
var s3Files = [];
function s3Key(link){
var parsedUrl = url.parse(link);
var fileName = parsedUrl.path.substring(1);
return fileName;
}
for(var k in file){
console.log('Here are each files ' + file[k].fileName);
s3Files.push(s3Key(file[k].fileName));
}
console.log('Here are the s3Files ' + s3Files);
//GOTTEN TO THIS POINT WITHOUT AN ERROR
aws.config.update({accessKeyId: process.env.AWS_ACCESS_KEY, secretAccessKey: process.env.AWS_SECRET_KEY, region: process.env.AWS_REGION});
//var awsKeyPath = s3Key(file.fileName);
var s3 = new aws.S3();
var options = {
Bucket: process.env.AWS_BUCKET,
Delete: {
Objects: [{
Key: s3Files
}],
},
};
s3.deleteObjects(options, function(err, data){
if(data){
console.log("File successfully deleted");
} else {
console.log("Check with error message " + err);
}
});
});
Here is the output from console.log('Here are each files ' + file[k].fileName);:
Here are each files https://local-bucket.s3.amazonaws.com/1/2017-02-12/screen_shot_2017-02-01_at_8_25_03_pm.png
Here are each files https://local-bucket.s3.amazonaws.com/1/2017-02-13/test.xlsx
Here are each files https://local-bucket.s3.amazonaws.com/1/2017-02-13/screen-shot-2017-02-08-at-8.23.37-pm.png
Here is the output from console.log('Here are the s3Files ' + s3Files);:
Here are the s3Files 1/2017-02-12/screen_shot_2017-02-01_at_8_25_03_pm.png,1/2017-02-13/test.xlsx,1/2017-02-13/screen-shot-2017-02-08-at-8.23.37-pm.png
Here is the error message:
Check with error message InvalidParameterType: Expected params.Delete.Objects[0].Key to be a string
Key should be a string. You should use array of Object to Objects.
Use this code :
var objects = [];
for(var k in file){
objects.push({Key : file[k].fileName});
}
var options = {
Bucket: process.env.AWS_BUCKET,
Delete: {
Objects: objects
}
};
Change your array as an object
const objects = [
{Key: 'image1.jpg'},
{Key: 'image2.jpg'}
]
Add a new item to the list
for(var k in file){
objects.push({Key : file[k].fileName});
}
Set the array as Objects value in parameters
const options = {
Bucket: process.env.BUCKET,
Delete: {
Objects: objects,
Quiet: false
}
};
Now delete objects
s3.deleteObjects(options, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Learn more from official docs

How to clear an array in MongoDB

I have an emails object that contains an array in a mongodb database. However, when I try to use $set to make the array empty it doesn't work. How am I supposed to clear the array?
exports.clearEmails = function(req, res, next) {
var listId = req.params.id;
var errors = req.validationErrors();
if (errors) {
return res.status(400).send(errors);
}
EmailList.update({'_id': listId}, {$set: {'emails': []}}, function(err,results) {
if (err) {
return res.status(400).send(err);
} else {
return res.status(200).send(results);
}
});
}

How to update mongoDB from post()

I am creating a MEAN Stack application. My post function is as follows:
app.post('/updateGroup/:id', function(req, res) {
var id = req.params.id; // = mongoDB ObjectID ie: "55616e2a37e8728266ceac6"
var vals = {};
vals['hostName'] = req.body.hostName // = a String ie, "Steve"
// this is a different name value than the
// current hostName key that is in
// the groupList db
db.groupList.update(
{"_id": id},
{$set : vals},
function(err, result) {
if (err) {
console.log(err);
}
else {
console.log(result);
}
}
);
});
When I access this function in my front-end Angular code my
console.log(result);
Comes out as:
{ ok: true, n: 0, updatedExisting: true }
But I should see n: 1 to indicate there was an update? Why is my Node application not updating my mongoDB key:value pair?
Is there something about db.collection.update() that I'm missing?
I was able to figure it out:
When assigning the _id query I needed to do it like this:
id['_id'] = mongojs.ObjectId(req.params.id);

Resources