Reputation: 305
I am trying to POST an array of objects to my MongoDB database using NodeJS. When I post, all my fields show up empty. I put my code below, and below that explain what each of the console.log
s output. Any ideas how to sort this out?
MODEL
var mongoose = require('mongoose');
var TransferSchema = new mongoose.Schema({
uploadDate: Date,
period: Number,
transferCode: String,
voucherNumber: String,
vendor: String,
description: String,
amount: Number
});
//convert schema to model
var Transfer = mongoose.model('Transfer', TransferSchema);
//export model for use elsewhere in app
module.exports = Transfer;
AJAX
- here I've tried posting both newArray
and json
. Both result in the same data posted to my db, but have a different effect on the console.log
s in the controller file.
console.log(newArray);
json = JSON.stringify(newArray);
console.log(json);
$.ajax({
url: "http://localhost:3000/transfers/api",
type: "POST",
data: newArray,
datatype: 'json',
success: function(data, textStatus, jqXHR) {
console.log('posted!');
},
error: function(data, textStatus, errorThrown) {
console.log('failed');
}
})
transferController.js
-when posting newArray
I get the following:
body: [object Object]
,
Body: {"undefined": ["", "", "", etc]
,
Text: undefined
,
Done: undefined
-when posting json
I get the following:
body: [object Object]
,
Body: {"{\"period\":5,\"uploadDate\":2015-11-19T21:00:00.000Z\",\"transferCode\":\"1041\",\"vendor\":\"Lakes State\",\"voucherNumber\":\"0000047571\",\"description\":\"1003-1555 Sal Tax Adj Gran Sep \",\"amount\":456802}...
,
Text: undefined
,
Done: undefined
//Create a new transfer
function createTransfer(request, response) {
console.log('posting');
console.log('body: ' + request.body); //TEST
console.info("Body: " + JSON.stringify(request.body)); //TEST
console.info("Text: " + JSON.stringify(request.body.text)); //TEST
console.info("Done: " + JSON.stringify(request.body.done)); //TEST
var transfer = new Transfer(request.body);
transfer.save(function(error) {
// console.log('transfer and transfer: ' + transfer);
if(error) return response.json({ message: 'could not create transfer because ' + error });
response.json({ transfer: transfer });
});
}
EDIT:
I tried using Insomnia to test what I'm sending. Weirdly, the below screenshot posts on Insomnia, but does not post in my app:
Also interesting, if I post several objects in an array using Insomnia, it does not work, as seen below:
Upvotes: 1
Views: 5732
Reputation: 306
Try setting contentType: 'application/json'
in your ajax request and stringify your data like so JSON.stringify(newArray)
. This should ensure the data you are sending up is ok.
It looks like you are sending up many transfers but then trying to create one transfer from all the data (request.body
)? You would need to loop over them and create them individually. Something like this:
request.body.forEach(function(obj) {
var transfer = new Transfer(obj);
transfer.save();
});
Upvotes: 4