mongoose insert document for each ajax call - javascript

I'm trying to insert data into MongoDB using Mongoose, i created a form and sending data using two ajax post to the node, but Mongoose insert two document for each ajax call, I want to send my data to data as a single document.
This my server:
app.post("/cp" , upload , function(req , res){
console.log('file uploaded succcessfully');
var title = JSON.stringify(req.body.titles);
var file = req.file;
const courses = new Courses({
// courseTitle:c_title,
// courseSubtitle:c_subtitle,
// courseAuthor : c_creator,
// coursePrice : c_price,
courseVideo :file ,
courseTitles :title ,
// courseSpecs : c_specs,
courseValidation : 0
});
courses.save();
});
Mongoose insert a document with title and without file and a document with file and without title,
Ajax:
if(e.submitter.id == "submitpostCp"){
var data = {};
data.titles = titlesLis;
data.specs = specsLis;
data.submit = "submitAll";
var fileup = new FormData($('#form')[0]);
$.when(
$.ajax({
type: 'post',
url: '/cp',
data: JSON.stringify(data),
contentType: 'application/json',
xhrFields: {
withCredentials: false
},
headers: {
},
success: function (data) {
console.log('Success');
console.log(data);
},
error: function () {
console.log('We are sorry but our servers are having an issue right now');
}
})
).then(function() {
$.ajax({
url:'/cp',
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: fileup,
success: function(res){
// alert(res);
},
error: function(){
alert('Error: In sending the request!');
}
})
});
}

In this case you should use findOneAndUpdate method with options {upsert: true}: https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate

Related

Wrong textarea.value while making ajax calls to server side

I have a text area with id "text" and I am toggling the text area to appear on the screen with a click event on some div and I have 30 such divs.
Initially , I'm assigning the textarea.value with result of ajax call to my fetch api which fetches the data from the mongo on the server side based on an unique id.
Sometimes , when I'm making the ajax call to my update api in my backend , the textarea.value I'm sending as data to this ajax call is not the same as the updated text of the text area.
//client side
// called when any of the divs is clicked
$(".radius").on("click", function(event) {
//extracting the id from the class and using this id as the id of my data for my mongo
var st=event.target.classList[1].substring(0,7);
var num=parseInt(event.target.classList[1].substring(7));
var toadd="close-button"+num;
//console.log(num+"modal")
closeButton.classList.add(toadd);
$.ajax({type: "POST",
url: "/fetch",
async: true,
data: JSON.stringify({
id: num,
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
input.value=result.text;
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
});
// called when textarea is closed
function toggleModal1(event) {
var s1=closeButton.classList[closeButton.classList.length-1];
var st=s1.substring(12);
closeButton.classList.remove(s1);
var num=parseInt(st);
// event.preventDefault();
console.log(input.value)
$.ajax({type: "POST",
url: "/update",
data: JSON.stringify({
id:num,
text:input.value,
//input is my textarea
}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success:function(result) {
},
error:function(result) {
console.log("error")
}
});
modal.classList.toggle("show-modal");
}
//server side
app.post("/fetch",function(req,res)
{
//console.log(req.body);
// var id1=req.body.id;
const findInDB= Fruit.findOne({id:req.body.id},function (err, docs) {
console.log(docs);
res.send({text:docs.text});
});
});
app.post("/update",function(req,res)
{
Fruit.updateOne({id:req.body.id},
{text:req.body.text}, function (err, docs) {
if (err){
console.log(err)
}
else{
console.log("Updated Docs : ", docs);
}
});

Upload Metadata with Multiple Files in laravel

I want to upload multiple files in laravel with metadata. Like file custom name and file category.
I tried to add some property in frontend using js but I can see them in the controller
here the code
$(document).on('change','#file',function(e){
let file = e.target.files[0]
file.totalWords = 1234;
file.caytegory = 'category';
filesList.push(file)
});
let mainFormData = new FormData();
filesList.forEach(file => {
mainFormData.append('files[]',file)
})
$.ajax({
data: mainFormData,
url: 'controller_url',
type: "POST",
processData: false,
contentType: false,
headers: {
Accept : "application/json"
},
success: function (data) {
console.log(data)
});
},
error: function(response) {
console.log(response);
}
});
And here is my controller
return response()->json($request->file('files')[0]->caytegory);
What I want is just to access the category property from the submitted file but I cann't

Array via POST (Ajax)

Okay, this seems to be the most straight forward thing, but I really have no idea why it's doing this nor find anyone else with this problem.
Here's my issue, I'm sending a POST request like so;
$.ajax({
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
In the data object is an array called items. When I log the data object it's fine, like it should be, however when I log the data object in my express function the items array changes to items[] for no reason..
NodeJS
'items[]': '15716345'
JS (Browser)
items: [15716345]
Any idea what's happening here?
Below is the entire version of the code.
Entire block (frontend)
// Validate address
if($('.block.payment .wrapper input:eq(0)').val() !== $('.block.payment .wrapper input:eq(1)').val()){
return error('Fields do not match');
}
// Get known data
var type = $('.body.inventory .methods .method.selected').data('type'),
items = [];
var data = {
type,
address: $('.block.payment .wrapper input:eq(0)').val()
}
if(type === 'steam'){
var app = $('.body.inventory .sub-methods .method.selected').data('app');
data['app'] = app;
$('.body.inventory .item[data-app="'+app+'"].selected').each(function(){
items.push($(this).data('id'));
});
}else{
$('.body.inventory .item[data-type="'+type+'"].selected').each(function(){
items.push($(this).data('id'));
});
}
data['items'] = items;
// Execute route or smt
$.ajax({
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
Backend
router.post('/sell', function(req, res, next) {
try {
console.log(req.body);
res.send({
success: 1
});
} catch(e) {
if(e) console.log(e);
res.send({
success: 0,
error: e
});
}
});
Set JSON body parser middleware for requests to your expressJS application.
const bodyParser = require('body-parser');
app.use(bodyParser.json())
And in the AJAX request, make the contentType to be application/json and not the default of application/x-www-form-urlencoded; charset=UTF-8'.
$.ajax({
contentType: 'application/json',
type: "POST",
url: '/user/sell',
data: data,
success: function(data) {
console.log('Call was successful');
}
});
Assume that is your Array List, which you want to POST.
object[] Obj = new object[1];
Obj [0] = "value1"
Obj [1] = "Value2"
Obj [3] = {"CollectionValue1, CollectionValue2"}
$.ajax({
url: '../Controller/MethodName',
type: 'post',
datatype: 'json',
async: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ ControllerParameterName: Obj }), <!-- Obj is your Array -->
success: function (data) {
alert(data.Response);
}
});

How can I send the image using Ajax

I want to know how can I send the image data to the server (Django app) using javascript ajax function.
Following is my code.
// Get filename of image
jsondata = JSON.parse(data);
image_file_name = jsondata.fileurl;
// document.getElementById('previewimage').src = image_file;
// I can show the image.
b64_image = btoa(unescape(encodeURIComponent(image_file)));
var credentials = {
filename: image_file_name,
image: b64_image,
};
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'GET',
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
jsondata = JSON.parse(data);
alert("File upload completed...");
})
// If false...
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
You have to use FromData for posting files using ajax .
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
// success code .
}
});
You just need to make one change in your code.
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'POST', // changed from GET to POST
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
as GET is use to read and post is used to create.
you can read more about request methods.

ajax request posting undefined data from form in nodejs

I am trying to make a comment form which adds a comment in array of blog schema
but when I am using ajax it is giving undefined below the places where I have console log and when I am using simple post request it is working fine.
I am using mongoose, nodejs , express, jquery ajax
my script is as follows
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
function addNewComment(data){
console.log(data);
}
my routes is as follows
//add comments
router.post('/addComment',function(req,res,next){
console.log(req.body.comment+" "+ req.body.userId+" "+req.body.postId);
var newComment = {
'text': req.body.comment,
'author': req.body.userId
}
Post.addComment(req.body.postId, newComment, function(err,comment){
if(err) throw err;
console.log(comment);
res.send(comment);
});
});
and my mongoose schema is
//add comments
module.exports.addComment = function( postId, newComment, callback){
var query = { '_id': postId};
console.log('postid: '+postId+" newcomment: "+newComment.text+ " "+newComment.author);
Post.findOneAndUpdate( query, { $push:{'comments': newComment} }, {new:true} , callback);
}
That's because data is not defined in ajax call ,
use following provide the frm is the actallu form or use
use data : form name.serialize()
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
data : $(this).serialize(),
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});

Categories