I'm trying to post data using postman, but when I tried to use multiple documents, it shows blank in my mongodb. But when I try to insert a single document, it saves the data. Please correct me, I'm new to this
server.js
app.post('/bloodinventory', function(req, res) {
var bloodinventory= new Bloodinventories();
bloodinventory.blood_group = req.body.blood_group;
bloodinventory.blood_category = req.body.blood_category;
bloodinventory.num_stock = req.body.num_stock;
bloodinventory.save(function(err) {
if (err) {
res.json({ success: false, message: 'Blood Donation already exists!' });
} else {
res.json({ success: true, message: 'Blood Donation Created!' });
}
});
});
Then in my postman, I tried to insert this data:
{
"bloodinventories":[
{
"blood_group":"A_positive",
"blood_category":"whole blood",
"num_stock":11
},
{
"blood_group":"A_negative",
"blood_category":"platelet",
"num_stock":9
}
]
}
Then nothing shows in my mongodb, result:
_id:5c45c6a495788ec2c47f8c8b
__v:0
When you provide single document in your POST request
Example:-
{
"blood_group":"A_positive",
"blood_category":"whole blood",
"num_stock":11
}
it easly get request.body.blood_group, request.body.blood_category and show on
But when you pass Mutliple document in POST request in array form
{
"bloodinventories":[
{
"blood_group":"A_positive",
"blood_category":"whole blood",
"num_stock":11
},
{
"blood_group":"A_negative",
"blood_category":"platelet",
"num_stock":9
}
]
}
Now your request is getting a array so your request body contain bloodinventories. And you can access it as request.body.bloodinventories
Take this const and apply loop on it and insert all document.
Or Simply make API like this and always send array in every request of insert.
Bloodinventories.insertMany(request.body.bloodinventories).then((result) => {
//Success Message
}).catch(err => {
// Error Message
});
It May Help For You...
Related
I am trying to create a (MERN stack) management system that keeps track of vacant rooms in a hotel.
I am trying to change the roomTypeAOccupiedTotal from 2 to 3.
From the client side, it sends an axios.put()request as follows:
axios
.put(`http://localhost:8082/api/myHotel/${branchStatus.id}`, data)
this is the server-side code:
router.put('/:_id', (req, res) => {
/*
req.params looks like this:
{ _id: '63b4d533fabbf31cdb519896' }
req.body looks like this:
roomOccupied5F: 3,
roomOccupied6F: 5,
roomTypeAOccupiedTotal: 2,
roomTypeBOccupiedTotal: 8,
*/
let filter = { _id: mongoose.Types.ObjectId(req.params._id) }
let update = { $set: req.body }
MyHotel.findByIdAndUpdate(filter, update, {new: true})
.then(data => res.json({ msg: 'updated successfully' }))
.catch(err =>
res.status(400).json({ error: 'Unable to update the Database' })
);
Below are the GET request and PUT request sent using POSTMAN.
after the message "updated successfully", I sent another GET request to check, but there are no changes to the variable(roomTypeAOccupiedTotal).
Could someone help me with solving this problem? the findByIdAndUpdate() method is working, as its not throwing any errors, but its not updating.
I believe your problem is the filter object. Looking at the docs for findByIdAndUpdate, it expects to receive the id param, not a filter object.
https://mongoosejs.com/docs/api/model.html#model_Model-findByIdAndUpdate
Parameters:
id «Object|Number|String» value of _id to query by
Additionally, when you create an objectId out of the request param, you aren't creating a new instance of it, so whatever was passed in would have failed to match anything. My IDE highlights this for me:
Your fix is likely something like this:
const id = new mongoose.Types.ObjectId(req.params._id)
MyHotel.findByIdAndUpdate(id, update, {new: true})
No need to convert id, and no need to use the update operator(i.e. $set).
try this:
MyHotel.findByIdAndUpdate(req.params._id, req.body, { new: true }, (err, hotel) => {
if (err) {
console.log(err);
} else {
console.log(hotel);
}
});
I'm making app with MEAN stack and I want on every get request to increase viewCounter on specific document ( Property ) inside collection.
If i put this code inside get request of requested property
Property.findByIdAndUpdate('id', { $inc: { counter: 1 } }, {new: true})
It will increase loading of data and i want to do that after user gets his data.
So is the best way to do this just to send additional request to the database after initial data is loaded ?
Property {
name: '',
description: '',
...,
viewCounter: 5
}
exports.getProperty = catchAsync(async (req, res, next) => {
query = await Property.findById(req.params.id).lean();
if(!query) {
return next(new AppError('No property found with that ID', 404))
}
res.status(200).json({
status: 'success',
data: {
query
}
})
})
Node events can be used to keep the counter of events.
Official document
Reference for code
eventEmitter.on('db_view', ({ parameters }) => {
eventTracker.track(
'db_view',
parameters
);
})
eventEmitter.on('db_view', async ({ user, company }) => {
Property.findByIdAndUpdate('id', { $inc: { counter: 1 } }, {new: true})
})
Try to send request after making sure your document has loaded.
angular.element($window).bind('load', function() {
//put your code
});
I am trying to batch delete using deleteMany via Mongoose. Currently I have a few rows with check-boxes and a submit button which POSTs an array of IDs to my deleteMany endpoint like this,
router.get('/list/batchDelete', secured()).delete(function(req, res) {
Booking.deleteMany(
{
_id: {$in: [req.params.ids]},
},
function(err, rowsToDelete) {
if (!err) {
res.send(rowsToDelete);
res.redirect('/list');
} else {
res.send(err);
console.log('Error in batch delete :' + err);
}
},
);
});
I can see the req.params.ids payload.
POSThttp://localhost:8000/list/batchDelete
[HTTP/1.1 404 Not Found 34ms]
Request payload
ids%5B%5D=5e1da4db2f11682b506fc6c8&ids%5B%5D=5e1da522becbb13f24748012&ids%5B%5D=5e1da57a5c7f911db82e5731
But I keep getting Cannot POST /list/batchDelete
Please, what am I missing?
I referred to:
Mongoose Delete Many by Id
Mongoose Docs: Query.prototype.deleteMany()
UPDATE:
I added a post route like this, which now produces 200OK but in the browser JSON view and still no change to the dataset.
router.post('/list/batchDelete', function(req, res) {
const ids = req.body.ids;
res.send(ids);
res.redirect('/list');
});
Use your route like this
router.post('/list/batchDelete', async (req, res) {
const {ids} = req.body;
await Booking.deleteMany(
{
_id: {$in: ids},
})
return res.send('record deleted');
});
Use postman for api call
Call should be POST and on /list/batchDelete route
Body should contain array of ids
e.g {"ids":['id1','id2']}
This will solve your problem of deleting records.
I have this function on my backend:
exports.updatePacienteByCodigo = function (req, res) {
let codPaciente = req.params.codPaciente;
let params = req.body; // This is the data what come from frontend = {'testRealizados':['example'], 'respuestas':['example'], 'codMedico':'example'}
Paciente.findOneAndUpdate({ codPaciente: codPaciente }, {
'$push': {
'testsRealizados': params.testsRealizados,
'respuestas': params.respuestas,
'codMedico': {'$ne':params.codMedico} //here is the problem
}
}).then(
pacienteEncontrado => {
if (!pacienteEncontrado) {
res.status(404).send({ accion: 'updatePaciente', mensaje: 'Ese paciente no existe' });
} else {
res.status(200).send({ accion: 'updatePaciente', mensaje: 'Paciente actualizado correctamente' });
}
}
).catch(err => { res.status(500).send({ accion: 'updatePaciente', mensaje: 'Error ' + err }) })
};
This query throw me this error "Error CastError: Cast to [string] failed for value \"[{\"$ne\":\"o8qjdeli\"}]\" at path \"codMedico\""}
What I want to do is, if codMedico have the same value in the database than the param codMedico dont update that field.
I tried that but that didnt work. I am out of ideas so here I am. Thanks.
[SOLVED]
I tried with $addToSet method and it works perfectly like #Plancke told me in the comments.
I tried with $addToSet method and it works perfectly like #Plancke told me in the comments.
I am new to Node.js and I'm facing an error :
RangeError: Maximum call stack size exceeded
I'm not able able to solve the problem because most of the stack problems in others stackoverflow questions about Node.js deals with hundreds of callback but I have only 3 here.
First a fetch (findById) then an update an later a save operation!
My code is :
app.post('/poker/tables/:id/join', function(req, res) {
var id = req.params.id;
models.Table.findById(id, function(err, table) {
if (err) {
console.log(err);
res.send({
message: 'error'
});
return;
}
if (table.players.length >= table.maxPlayers) {
res.send({
message: "error: Can't join ! the Table is full"
});
return;
}
console.log('Table isnt Full');
var BuyIn = table.minBuyIn;
if (req.user.money < table.maxPlayers) {
res.send({
message: "error: Can't join ! Tou have not enough money"
});
return;
}
console.log('User has enought money');
models.User.update({
_id: req.user._id
}, {
$inc: {
money: -BuyIn
}
}, function(err, numAffected) {
if (err) {
console.log(err);
res.send({
message: 'error: Cant update your account'
});
return;
}
console.log('User money updated');
table.players.push({
userId: req.user._id,
username: req.user.username,
chips: BuyIn,
cards: {}
});
table.save(function(err) {
if (err) {
console.log(err);
res.send({
message: 'error'
});
return;
}
console.log('Table Successfully saved with new player!');
res.send({
message: 'success',
table: table
});
});
});
});
});
The error occurs during the save operation at the end!
I use MongoDb with mongoose so Table and User are my database collections.
This is from my first project with Node.js,Express.js and MongoDB so I probably have made huge mistakes in the async code :(
EDIT: I tried to replace the save with an update:
models.Table.update({
_id: table._id
}, {
'$push': {
players: {
userId: req.user._id,
username: req.user.username,
chips: BuyIn,
cards: {}
}
}
}, function(err, numAffected) {
if (err) {
console.log(err);
res.send({
message: 'error'
});
return;
}
console.log('Table Successfully saved with new player!');
res.send({
message: 'success',
table: table
});
});
But it doesn't help the error is still coming and I don't know how to debug it :/
I've been passing for this problem too.
Basically, when you have a property with a ref, and you want to use it in a find, for example, you can't pass the whole document.
For example:
Model.find().where( "property", OtherModelInstance );
this will trigger that error.
However, you have 2 ways to fix this for now:
Model.find().where( "property", OtherModelInstance._id );
// or
Model.find().where( "property", OtherModelInstance.toObject() );
This may stop your problems for now.
There is a issue in their GitHub repo where I reported this, however it's without fix for now. See the issue here.
I kept getting this error and finally figured it out. It's very hard to debug since no real information is presented in the error.
Turns out I was trying to save an object into a field. Saving only a specific property of the object, or JSON stringifying it, worked like a charm.
Seems like it would be nice if the driver gave a more specific error, but oh well.
MyModel.collection.insert causes:
[RangeError: Maximum call stack size exceeded]
When you pass array of instances of MyModel instead of just array with values of that objects.
RangeError:
let myArray = [];
myArray.push( new MyModel({ prop1: true, prop2: false }) );
MyModel.collection.insert(myArray, callback);
No error:
let myArray = [];
myArray.push( { prop1: true, prop2: false } );
MyModel.collection.insert(myArray, callback);
There are a few ways to debug nodejs applications
Built-in Debugger
The Node.js debugger is documented here: http://nodejs.org/api/debugger.html
To place breakpoints, simply put debugger; at the place you want to break. As you said the table.save callback is giving you troubles, you could put a breakpoint inside that function.
Then you run node with the debugger enabled:
node debug myscript.js
And you will get more helpful output.
Investigating the stack
You can also use console.trace to print a stacktrace, if you have a good idea of when/where you run into problems, and want to figure out how you got there.
Good luck, I hope this helps!