In my NodeJS project, I have created a mongoose schema which I changed midway through the project. More specifically, I added the unique parameter to a field.
However, this change does not seem to reflect as I am still able to create multiple documents with the same value for the parameter which I set as unique
How to fix this issue
Mongoose enforces the unique constraint by creating an index in MongoDB with the unique option.
If you already have duplicates in the collection, that index creation will fail.
Note that you may have to call syncIndexes to update the database with the new index.
Related
I was wondering. I have a lot of coding to do with a function to remove a document from the database. Basically removing just the object is not that much work, but removing the _id reference from all the other models step by step in the right order is the big work load (I pushed the object ID into the other objects so I could create relations and populate later).
I was wondering: is there no function standard in mongoose that instantly removes the document as well as all its objectId references in the documents of the other model types (so completely remove the object and all it's ObjectID references in all the other collections in the DB)?
You can achieve what you are looking for using this NPM package called
cascading-relations here
I would like to generate a unique ObjectId for a resource to give back clients with the nodejs mongodb driver.
IE:
var ObjectID = require('mongodb').ObjectID;
var objectId = new ObjectID();
Reading about an ObjectId it seems that there are some cases in which this id may not be unique. Even though this is extremely rare I still cannot take a chance on having a duplicate id.
Question #1, Using this driver is it possible (even though unlikely) to get a duplicate id doing this:
var objectId = new ObjectID();
Question #2 (if above is not 100% guarantee to give a unique id):
Does this driver guarantee that for a certain collection the ObjectId that is automatically created when a new document is inserted is unique? If yes, how? If yes, can I somehow duplicate that behavior when calling new ObjectID() myself without a collection?
If the driver or the mongo server ensures (100% of the time) that for a collection every new doc gets a unique id, I could always have a collection of just ids, then when generating a new, empty doc for that collection I would ensure I get a unique ObjectId. However seems like overkill to have another collection just to store ids.
That being said some might ask why not just generate the ObjectId in a collection and update that doc later with data. The answer is that in my case data may not ever come later and I don't want to implement logic to check for empty docs that only contain an id.
It's very unlikely that the same ObjectID will generate as mongo guarantees unique ID. objectID is created with a combination of two same values and two different values (unix epoch time, and a random value). However, in any case of a duplicate, you won't be allowed to insert a document as objectID acts as a primary key and insert function will return duplicate key error to your callback. Read more here. The same error is returned if mongo node native library creates a duplicate ObjectID.
UPDATE: again after reading the code base, if "hypothetically" the objectID that was generated by the library isn't unique, the answer is no. We are not ensured by the library that the id is unique, but we are ensured of a duplicate error doesn't matter who or what sent the id.
Here's the process:
1. generates ID
2. Sends straight to server.
3. Returns results.
Mongo isn't looping in nodeJS with existing ids because the library isn't storing it in cache. Read the code base for the library.
Hi all I'm new to learning how to develop with Node.js using Mongoose and Express. I have been having some issues with Mongodb not correctly reflecting my schema changes.
For example, I have written a model that supposedly auto-increment _id by 1 starting from 0 when each new document is inserted. I'm testing a few ways to do this model and so I'm constantly inserting different data.
I drop the collection each time to try to reinsert the data. However, _id instead of starting at 0, it starts at the previous largest _id.
This is just one of the issues that I have encountered. Some other similar Schema changes that I did on the fly also were not reflected.
I tried the following:
Ending npm/nodemon
Ctrl+C from mongo
shutdownServer from mongo
Is there something else that I need to shut down completely then restart before mongoose reflects the newest form of the schema? Thanks!
To start fresh with a new schema, it's best (if possible) to drop the old database entirely (db.dropDatabase() from the MongoDB shell), otherwise you may run into various issues (that can also be solved separately, if dropping the database isn't an option):
left-over collections, like the one used by the autoincrement plugin that you're using (I think it'll use a collection called identitycounters);
left-over indexes, which happens when you define field names in your schema that should be indexed, and you subsequently rename or delete one of those fields;
Restarting the database server won't solve these, they do require some manual administration.
I am trying to create a slug(prettyurl) for each post added by the user. And use this slug to access the record in the db. The generated slugs might not be unique so I thought of adding the #rid at the end of the slug. So that the slugs will be unique and I can retrieve the record with the #rid while fetching the record. I can use this slug in the restful url's as well(after removing the # in the #rid).
So is there a way to append the rid to the slug property while inserting the record?
Or is there an auto increment field in orientdb which I can concatenate with the slug?
Or is there any other way to achieve the same result? I thought about generating a unique id from node js but this might add the overhead of creating and managing unique filed across multiple servers.
I am using
orientjs version: 2.1.0
orientdb version 2.1.6
Slug thing what you have explained I can not understand.
However #rid that is the Record Identifier in OrientDB is unique and it resembles like Primary Key of our Relational Database System.
to append the #rid you can use slug.append(#rid) but at the time of INSERT, it may not work as #rid is determined after the INSERT.
You can use INSERT.. RETURN #rid read it from here
However, for the Auto Increment purpose, I would say that #rid is automatically incremented. It is decided as #clusterIDOfTheRecord:positionOfTheRecordInTheCluster.
So, autoincrement there may not be needed.
I'm playing around with quick start guide for mongoose.
http://mongoosejs.com/docs/index.html
I assumed that it would throw an error when I saved a document with a field NOT defined in the schema. Instead, it created a new document in the collection but without the field. (Note: I realize mongodb itself is "schema-less" so each document in a collection can be completely different from each other.)
two questions
How does mongoose handle adding documents that have fields that are NOT part of the schema? It seems like it just ignore them, and if none of the fields map, will create an empty document just with an ObjectId.
And how do you get mongoose to warn you if a specific field of a document hasn't been added even though the document successfully saved?
(The question is - I believe - simple enough, so I didn't add code, but I definitely will if someone requests.)
Thanks.
Q: How does mongoose handle adding documents that have fields that are NOT part of the schema?
The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db.
- mongoose docs
Q: How do you get mongoose to warn you if a specific field of a document hasn't been added even though the document successfully saved?
The strict option may also be set to "throw" which will cause errors
to be produced instead of dropping the bad data. - mongoose docs
...but if you absolutely require saving keys that aren't in the schema, then you have to handle this yourself. Two approaches I can think of are:
1. To save keys that aren't in the schema, you could set strict to false on a specific model instance or on a specific update. Then, you'd need to write some validation that (a) the values in the document conformed to your standards and (b) the document saved in the database matched the document you sent over.
2. You could see if the Mixed schema type could serve your needs instead of disabling the validations that come with strict. (Scroll down to 'usage notes' on that link, as the link to the 'Mixed' documentation seems broken for the moment.)
Mongoose lets you add "validator" and "pre" middleware that perform useful functions. For instance, you could specify the required attribute in your schema to indicate that a specific property must be set. You could also specify a validator that you can craft to throw an error if the associated property doesn't meet your specifications. You can also set up a Mongoose "pre" validator that examines the document and throws an Error if it finds fields that are outside of your schema. By having your middleware call next() (or not), you can control whether you proceed to the document save (or not).
This question/response on stackoverflow can help with figuring out whether or not an object has a property.