Implementing DELETE endpoint with my Restful API [duplicate] - node.js

How can I check if the remove-method of a Mongoose model really has removed something?
MyModel.remove({_id: myId}, function(err, entry) {
if(entry == null) next(new Error("ID was not found.")); // this doesn't work
}
Can I check how many documents were removed?
In the Mongo-Documentation kristina1 write in a comment:
If you call db.runCommand({getLastError:1}) after a remove and the "n" field will tell you how many documents were deleted.
But I don't know how to do this with Mongoose.

Mongoose < 4, MongoDB < 3
The second parameter to the remove callback is a number containing the number of documents removed.
MyModel.remove({_id: myId}, function(err, numberRemoved) {
if(numberRemoved === 0) next(new Error("ID was not found."));
}
Mongoose 4.x, MongoDB 3.x
The second parameter passed to the remove callback is now an object with the result.n field indicating the count of removed documents:
MyModel.remove({_id: myId}, function(err, obj) {
if(obj.result.n === 0) next(new Error("ID was not found."));
}

I tried this with latest version of mongoose, and it did not work. As the second parameter comes back as operation result, not just count. Used as below, it worked :
Model.remove({
myId: req.myId
}, function(err, removeResult) {
if (err) {
console.log(err);
}
if (removeResult.result.n == 0) {
console.log("Record not found");
}
Console.log("Deleted successfully.");
});

I stumbled upon this in 2020 and found with Mongoose 5.9.28 that the result no longer requires a result wrapper, so using remove to get a count of deleted records in an async method looks like:
async function remove(query) {
const result = await ItemModel.remove(query);
return result.n;
}
Of course, collection.remove is deprecated in favor of deleteOne or deleteMany, so try this as well.

Related

Show entire MongoDB contents in Node.js API

First off, don't worry, it's a tiny data set - I realise it wouldn't be wise to dump an entire production DB to a single screen via an API... I just need to get a JSON dump of entire (small) DB to return via an API endpoint in a Node.js application.
My application does successfully return single records with this code:
MongoClient.connect("mongodb://localhost:27017/search", function (err, db) {
if(err) throw err;
db.collection('results', function(err, collection) {
// search for match that "begins with" searchterm
collection.findOne({'string':new RegExp('^' + searchterm, 'i')}, function(err, items){
// get result
var result;
if (items == null || items.result == null){
result = "";
}
else {
result = items.result;
}
// return result
res.send(result);
});
});
});
So I know Node is talking to Mongo successfully, but how can I tweak this query/code to basically return what you get when you execute the following on the MongoDB command line:
$ db.results.find()
This is snippet.
model.find({}).exec(function (err, result) {
if (err) {console.error(err); return;}
else return result;
});
First use your predefined model and call find. the logic is to place a empty object {} essentially rendering . select all from this model.
Make sense?
Exactly as you've described it.
collection.find({}).exec((err, result) => {
if (err) {
console.log(err);
return;
}
if (result.length > 0) {
// We check that the length is > 0 because using .find() will always
// return an array, even an empty one. So just checking if it exists
// will yield a false positive
res.send(result);
// Could also just use `return result;`
});
Thanks guys, I appreciate your answers pointing me in the right direction, in terms of using {} as the query. Here is the code that eventually worked for me:
db.collection('results', function(err, collection) {
collection.find({}).toArray(function(err, docs) {
res.send(docs);
});
});
The crucial element being the toArray(...) part.

Using findOne then save() to replace a document, mongoose

I want to use the validation in my schema. Therefore i can't use findOneAndUpdate (?). I must use save.
Problem is, if I use findOne, then replaces the object with the one I'm going to replace it with, it will no longer have the save function.
mongoose.model('calculations').findOne({calcId:req.params['calcId']}, function(err, calculation){
if(err) {errHandler.serverErr(err, res, 'Something went wrong when trying to update a calculation'); return;}
calculation = calculationToReplace;
calculation.save(function(err, calc){ //No longer exists
if(err) {errHandler.serverErr(err, res, 'Something went wrong when trying to update a calculation'); return;}
res.send(200);
});
});
This must be a common task but I can't find any solution. How do I fix this?
There is a simple solution to your (by now really old) question.
In my case I had to have a findOneAndUpdate upsert that returned more information on what happened. So my solution was to step through the process to update the object with a for loop.
(Think the reason why you can't just copy is that the doc object contains a bunch of "extras" like version information and save function and other "bits"); So here is my solution.
exports.postData = function(req,res) {
console.log("will create " + req.body.alias);
console.log("It is level " + req.body.level); //OK, all this have to be changed to members of the data! req.body contains all the data sent from the user at this time
var query = { 'fulltext' : req.body.fulltext};
console.log("Checkking if " + req.body.fulltext + " exists")
Skill.findOne(query, function (err,doc){
if(err) return res.status(500).send(err)
if (!doc){
console.log(req.body.fulltext + " not found!")
var newdoc = new Skill(req.body);
newdoc.save(function(err){
if(err) return res.status(500).send(err)
console.log(newdoc.fulltext + " created as " + newdoc._id);
return res.status(200).send({_id: newdoc._id, alias: newdoc.alias})
})
return res.status(200).send('blal')
} else {
console.log(req.body.fulltext + " found!")
for (var id in req.body ){
doc[id]= req.body[id];
}
doc.save( function(err){
if(err) return res.status(500).send(err)
return res.status(200).send({_id: doc._id, alias: doc.alias})
})
//return res.status(200).send({_id: doc._id, alias: doc.alias})
}
I have not tested the following, so I am not sure if this works properly but it should probably be fine:
Swap this:
calculation = calculationToReplace;
with this:
for (var key in calculationToReplace)
if(typeof calculation[key] !== 'function')
calculation[key] = calculationToReplace[key];
Yes there is a way. You can read the mongoose documentation here. Take a look at the following code.
Tank.findById(id, function (err, tank) {
if (err) return handleError(err);
tank.size = 'large';
tank.save(function (err) {
if (err) return handleError(err);
res.send(tank);
});
});
This approach involves first retreiving the document from Mongo, then issuing an update command (triggered by calling save).

mongoose: detect if document inserted is a duplicate and if so, return the existing document

This is my code:
var thisValue = new models.Value({
id:id,
title:title //this is a unique value
});
console.log(thisValue);
thisValue.save(function(err, product, numberAffected) {
if (err) {
if (err.code === 11000) { //error for dupes
console.error('Duplicate blocked!');
models.Value.find({title:title}, function(err, docs)
{
callback(docs) //this is ugly
});
}
return;
}
console.log('Value saved:', product);
if (callback) {
callback(product);
}
});
If I detect that a duplicate is trying to be inserted, i block it. However, when that happens, i want to return the existing document. As you can see I have implemented a string of callbacks, but this is ugly and its unpredictable (ie. how do i know which callback will be called? How do i pass in the right one?). Does anyone know how to solve this problem? Any help appreciated.
While your code doesn't handle a few error cases, and uses the wrong find function, the general flow is typical giving the work you want to do.
If there are errors other than the duplicate, the callback isn't called, which likely will cause downstream issues in your NodeJs application
use findOne rather than find as there will be only one result given the key is unique. Otherwise, it will return an array.
If your callback expected the traditional error as the first argument, you could directly pass the callback to the findOne function rather than introducing an anonymous function.
You also might want to look at findOneAndUpdate eventually, depending on what your final schema and logic will be.
As mentioned, you might be able to use findOneAndUpdate, but with additional cost.
function save(id, title, callback) {
Value.findOneAndUpdate(
{id: id, title: title}, /* query */
{id: id, title: title}, /* update */
{ upsert: true}, /* create if it doesn't exist */
callback);
}
There's still a callback of course, but it will write the data again if the duplicate is found. Whether that's an issue is really dependent on use cases.
I've done a little clean-up of your code... but it's really quite simple and the callback should be clear. The callback to the function always receives either the newly saved document or the one that was matched as a duplicate. It's the responsibility of the function calling saveNewValue to check for an error and properly handle it. You'll see how I've also made certain that the callback is called regardless of type of error and is always called with the result in a consistent way.
function saveNewValue(id, title, callback) {
if (!callback) { throw new Error("callback required"); }
var thisValue = new models.Value({
id:id,
title:title //this is a unique value
});
thisValue.save(function(err, product) {
if (err) {
if (err.code === 11000) { //error for dupes
return models.Value.findOne({title:title}, callback);
}
}
callback(err, product);
});
}
Alternatively, you could use the promise pattern. This example is using when.js.
var when = require('when');
function saveNewValue(id, title) {
var deferred = when.defer();
var thisValue = new models.Value({
id:id,
title:title //this is a unique value
});
thisValue.save(function(err, product) {
if (err) {
if (err.code === 11000) { //error for dupes
return models.Value.findOne({title:title}, function(err, val) {
if (err) {
return deferred.reject(err);
}
return deferred.resolve(val);
});
}
return deferred.reject(err);
}
return deferred.resolve(product);
});
return deferred.promise;
}
saveNewValue('123', 'my title').then(function(doc) {
// success
}, function(err) {
// failure
});
I really like WiredPrairie's answer, but his promise implementation is way too complicated.
So, I decided to add my own promise implementation.
Mongoose 3.8.x
If you're using latest Mongoose 3.8.x then there is no need to use any other promise module, because since 3.8.0 model .create() method returns a promise:
function saveNewValue(id, title) {
return models.Value.create({
id:id,
title:title //this is a unique value
}).then(null, function(err) {
if (err.code === 11000) {
return models.Value.findOne({title:title}).exec()
} else {
throw err;
}
});
}
saveNewValue('123', 'my title').then(function(doc) {
// success
console.log('success', doc);
}, function(err) {
// failure
console.log('failure', err);
});
models.Value.findOne({title:title}).exec() also returns a promise, so there is no need for callbacks or any additional casting here.
And if you don't normally use promises in your code, here is callback version of it:
function saveNewValue(id, title, callback) {
models.Value.create({
id:id,
title:title //this is a unique value
}).then(null, function(err) {
if (err.code === 11000) {
return models.Value.findOne({title:title}).exec()
} else {
throw err;
}
}).onResolve(callback);
}
Previous versions of Mongoose
If you're using any Mongoose version prior to 3.8.0, then you may need some help from when module:
var when = require('when'),
nodefn = require('when/node/function');
function saveNewValue(id, title) {
var thisValue = new models.Value({
id:id,
title:title //this is a unique value
});
var promise = nodefn.call(thisValue.save.bind(thisValue));
return promise.spread(function(product, numAffected) {
return product;
}).otherwise(function(err) {
if (err.code === 11000) {
return models.Value.findOne({title:title}).exec()
} else {
throw err;
}
});
}
I'm using nodefn.call helper function to turn callback-styled .save() method into a promise. Mongoose team promised to add promises support to it in Mongoose 4.x.
Then I'm using .spread helper method to extract the first argument from .save() callback.

MongoDB Node findone how to handle no results?

Im using the npm mongodb driver with node.
I have
collection.findOne({query}, function(err, result) {
//do something
}
The problem is say I dont have any results, err is still null whether I find a result or don't. How would I know that there were no results found with the query?
I've also tried
info = collection.findOne(....
But the info is just undefined (it looked asynchronous so I didn't think it was the way to go anyway..)
Not finding any records isn't an error condition, so what you want to look for is the lack of a value in result. Since any matching documents will always be "truthy", you can simply use a simple if (result) check. E.g.,
collection.findOne({query}, function(err, result) {
if (err) { /* handle err */ }
if (result) {
// we have a result
} else {
// we don't
}
}
All of these answers below are outdated. findOne is deprecated. Lastest 2.1 documentation proposes to use
find(query).limit(1).next(function(err, doc){
// handle data
})
Simply as:
collection.findOne({query}, function(err, result) {
if (!result) {
// Resolve your query here
}
}
nowadays - since node 8 - you can do this inside an async function:
async function func() {
try {
const result = await db.collection('xxx').findOne({query});
if (!result) {
// no result
} else {
// do something with result
}
} catch (err) {
// error occured
}
}
If result is null then mongo didn't find a document matching your query. Have tried the query from the mongo shell?
collection.findOne({query}, function(err, result) {
if (err) { /* handle err */ }
if (result.length === 0) {
// we don't have result
}
}

NodeJS + Mongoose: Updating all fields on a Mongoose model

I'm building out an api using Node, MongoDB and Mongoose. One thing that is bugging me is that you can't seem to set multiple fields at once:
app.put('/record/:id', function(req, res) {
Record.findById(req.params.id, function(err, doc) {
if (!err) {
doc.update(req.params);
doc.save();
...
However, it seems that you have to work out the update query and run it on the Model object rather than on the document object. Unless you want to assign individual properties and run save() at the end.
Is there any way of accomplishing this without having to write a Mongo query?
jsaak's answer is good but doesn't work for nested objects. I elaborated on his answer by searching and setting nested objects.
I added these functions to a utility.js file
var _ = require('underscore');
exports.updateDocument = function(doc, SchemaTarget, data) {
for (var field in SchemaTarget.schema.paths) {
if ((field !== '_id') && (field !== '__v')) {
var newValue = getObjValue(field, data);
console.log('data[' + field + '] = ' + newValue);
if (newValue !== undefined) {
setObjValue(field, doc, newValue);
}
}
}
return doc;
};
function getObjValue(field, data) {
return _.reduce(field.split("."), function(obj, f) {
if(obj) return obj[f];
}, data);
}
function setObjValue(field, data, value) {
var fieldArr = field.split('.');
return _.reduce(fieldArr, function(o, f, i) {
if(i == fieldArr.length-1) {
o[f] = value;
} else {
if(!o[f]) o[f] = {};
}
return o[f];
}, data);
}
implement as:
var util = require('./utility');
app.put('/record/:id', function(req, res) {
Record.findById(req.params.id, function(err, doc) {
if (!err) {
utils.updateDocument(doc, Record, req.params);
doc.save();
...
Maybe this has changed since this question was first asked, but you can update multiple paths in Mongoose with the set method ike:
// object
doc.set({
path : value,
path2 : {
path : value
}
});
doc.save();
References
http://mongoosejs.com/docs/api.html#document_Document-set
direct updating is not recommended according to this document:
http://mongoosejs.com/docs/2.7.x/docs/updating-documents.html
i solved it like this:
Book.findOne({isbn: req.params.isbn}, function (err, book){
if (err) {
res.send(422,'update failed');
} else {
//update fields
for (var field in Book.schema.paths) {
if ((field !== '_id') && (field !== '__v')) {
if (req.body[field] !== undefined) {
book[field] = req.body[field];
}
}
}
book.save();
}
});
If you want to update the entire document , you can delete the document based on its id and store the entire object again.
That object must contain data for each and every fields of the mongo document.
Here is an example.
mongoDBCollectionObject.findOneAndRemove({ // -- it will delete the entire document
_id: req.body.fieldsdata._id // here fiedsdata is exact copy with modification of previous data
}, function(err, data) {
var newFieldsData = new mongoDBCollectionObject(fieldsdata); //-- fieldsdata updated data
newFieldsData.save(function(err, data) { // save document to that collection with updated data
if (err) {
console.log(err);
} else
res.json({
success: true
});
});
})
To clarify the question, it looks like you are taking the Request parameters and using those to find and update the given document.
Is there any way of accomplishing this without having to write a Mongo query?
The obvious answer is to update the Model object with the value from the Request. Which is what you suggest...
Unless you want to assign individual properties and run save() at the end.
But it seems like you don't want to do this? It sounds like you want to update the Model object directly from the Request object?
You can do this if you really want. You just loop through req.params and set the doc values where appropriate.
for(var i in req.params) {
if(req.params[i] != doc[i]){
doc[i] = req.params[i];
}
}
It should be as simple as this. However, you only want to do this if you have a whole bunch of validation code on the Model objects. The whole point to the Model is that you don't want to get random data in the DB. The line above will generically "set" the correct values, but you'll definitely need to include code for authentication, authorization and validation around that simple for loop.
try to updating the collection without the find, like this
Record.update({_id:req.params.id}, {$set: { field: request.field }}, {upsert: true}, function(err{...})
The option upsert create the document if not exist.
In case you have a new object and want to update whole object in the database, you can update multiple fields at once like this:
find the object
get all schema paths (fields)
save the new object.
SomeModel.findOne({ 'id': 'yourid' },function (err, oldObject) {
if (err) return handleError(err);
// get all schema paths (fields)
SomeModel.schema.eachPath(function(path) {
// leave __id and __v alone
if (path != '_id' && path != '__v') {
// update the data from new object
oldObject[path] = newObject[path];
}
})
oldObject.save(function(err) {
if (err)
console.log(err)
});
})
A neat and clean approach would be using async await and findOneAndRemove along with create Here is the sample code
try {
let resp = await this.findOneAndRemove({ _id: req.body._id });
let entry = await this.create(req.body);
} catch (err) {
}
Don't Forget to mark this whole function as async

Resources