I wanted to delete certain set of documents in the mongo collection and insert new records, in case if the insert fails I want to rollback the delete. Basically, it is either both or none. Someone know what is the best approach for this. I'm using mongoose and nodejs.
Try to use promises. Insert one more field to your schema like isDeleted. When you delete some document set it to true and in the success of promise of delete, if the document successfully inserted delete that record permanently if you want.
Like this
db.collection.findOneAndUpdate(query)
.exec()
.then(
// write your insert logic here
db.collection.insert(query)
.exec()
.then()
.catch(
//if anything goes wrong set isDeleted
//to false again.
)
)
.catch()
I'd add a 'hidden' flag, then set the flag to true on some records insert new ones then depending on insert failure or success delete hidden objects or unhide them
What you need is a "Transaction".
A transaction is a unit of work, composed of a series of operations that you want either to succeed together, or fail together when one or more of the operations fail.
The following link explains in detail the use of transactions in nodejs and mongodb:
https://www.mongodb.com/docs/drivers/node/current/fundamentals/transactions/
Related
I have a basic express app and im getting started with db queries and i want to know how to avoid multiple db queries because i dont think its efficient the way i do it :
app.get('/:word', function(req,res){
db.create({'name': word});
console.log('the word is ' + word);
});
What i want to do is :
get the word from the url
check if it exists in the datbaase (or previously requested because if it was then it was probably added already through this basic code)
if it doesn't exist then add it and then proceed to console.log
I want to add each word to my database once only and not run the db query again and again.
Here's what im thinking :
Not so efficient way
query to check if it exists before inserting one
Good way but i dont know how to start here
Cache the word being queried and maintain cache to prevent db queries
More info edit
I'm using mongodb via mongoose
the 'word' key is already unique so i know its not creating duplicate values
i dont want to run ANY db queries if that value or that url has already been hit once
The only way to check if the word already exists is to query the database before inserting. There are libraries (and also database) that implements the findOrCreate method, but this is always just an abstraction. Behind the scenes, the database will search for an existing value before writing.
If your database is huge and queryng is not suitable, you could use a cashing system (like Redis). But this definitely depends on your logic and your data size.
Probably you can just optimize the process just adding and index to the column you want be unique (I guess it's name?).
You could also define the column name as unique. When inserting, the database will throw you an error if the document already exists. But keep in mind again that, behind the scenes, the database is queryng for an existing same value before inserting. The advantage to have an "unique" column is that the index for this column is automatically created and also from your app logic (node js) you can just call the insert method and add a little bit error handling logic.
MongoDB will create any collections you use in your app if they do not already exist.
Insert Unique Value :
Create Unique Index to your key, So that the value will be added only once. If you try to add again it will throws an error to you.
To create Unique Index,
db.collection.createIndex( { "name": 1 }, { unique: true } )
Caching :
For caching, Store your data on cache system(Like: memory-cache, redis) on first time data will be query from MongoDB and then for subsequent need of data you can use cache system.
In mongo db you can use findOneAndUpdate with optional flag upsert: true documentation
To ensure that every word appears only once you should also set unique index on that field. However rememer that unique index is case sensitive so Cat and cat are different words.
In my app I need a function that removes docs and giving me the removed doc fields. The docs for the driver are not clear about the callback of deleteMany. It returns a result that is deleteWriteOpResultObject. I don't know how to get the deleted doc fields from that.
You may use findAndModify operation with remove: true and fields: {your_fields} if you need to get and delete a single document. In case you have to remove and select multiple records, you may execute findAndModify multiple times or call find, wait the results and remove them all by IDs.
I am working on a node.js app, and I've been searching for a way around using the Model.save() function because I will want to save many documents at the same time, so it would be a waste of network and processing doing it one by one.
I found a way to bulk insert. However, my model has two properties that makes them unique, an ID and a HASH (I am getting this info from an API, so I believe I need these two informations to make a document unique), so, I wanted that if I get an already existing object it would be updated instead of inserted into the schema.
Is there any way to do that? I was reading something about making concurrent calls to save the objects, using Q, however I still think this would generate an unwanted load on the Mongo server, wouldn't it? Does Mongo or Mongoose have a method to bulk insert or update like it does with insert?
Thanks in advance
I think you are looking for the Bulk.find(<query>).upsert().update(<update>) function.
You can use it this way:
bulk = db.yourCollection.initializeUnorderedBulkOp();
for (<your for statement>) {
bulk.find({ID: <your id>, HASH: <your hash>}).upsert().update({<your update fields>});
}
bulk.execute(<your callback>)
For each document, it will look for a document matching the {ID: <your id>, HASH: {your hash}} criteria. Then:
If it finds one, it will update that document using {<your update fields>}
Otherwise, it will create a new document
As you need, it will not make a connection to the mongo server on each iteration of the for loop. Instead a single call will be made on the bulk.execute() line.
In mongoose I just added a pre condition to an existing model. This condition basically concatenate the values of all elements in the object, creates a hash and store it as another field in the same object.
This code will be executed on all elementes I will save from now on, but I was wondering if is possible to execute it also to all existing elements or if I have to write a script that updates them.
The records in your database will not be magically updated, you will have to update them manually for the first time.
If your new middleware works with updates you could find all your records and just save them. The middleware will be used and the new field will be populated.
Something like:
Model.find({}, function(err, records) {
records.forEach(function(record) {
record.save(function(err) { console.log(err); });
});
}
This will however be slow if your database is huge. In this case will be better updating the database directly.
I have a Tags collection which contains documents of the following structure:
{
word:"movie", //tag word
count:1 //count of times tag word has been used
}
I am given an array of new tags that need to be added/updated in the Tags collection:
["music","movie","book"]
I can update the counts all Tags currently existing in the tags collection by using the following query:
db.Tags.update({word:{$in:["music","movies","books"]}}, {$inc:{count:1}}), true, true);
While this is an effective strategy to update, I am unable to see which tag values were not found in the collection, and setting the upsert flag to true did not create new documents for the unfound tags.
This is where I am stuck, how should I handle the bulk insert of "new" values into the Tags collection?
Is there any other way I could better utilize the update so that it does upsert the new tag values?
(Note: I am using Node.js with mongoose, solutions using mongoose/node-mongo-native would be nice but not necessary)
Thanks ahead
The concept of using upsert and the $in operator simultaneously is incongruous. This simply will not work as there is no way to different between upsert if *any* in and upsert if *none* in.
In this case, MongoDB is doing the version you don't want it to do. But you can't make it change behaviour.
I would suggest simply issuing three consecutive writes by looping through the array of tags. I know that's it's annoying and it has a bad code smell, but that's just how MongoDB works.