Is there a way to generate an ID for a new document?
Something like
var newID = mongoose.Types.ObjectId();
// some random code that may involve db operations.
db.Model.create({_id: newID, otherProperties: {}})
When I write something like this, actual ID of the created document is always slightly larger than the newID. Is there anyway to use the newID exactly?
You should not create ID attribute for mongodb documents, It will automatically generate an ID attribute to all documents when we create them.
e.x
db.users.insert({name:'kasun',email:'kasun#gmail',address:'2street,colombo'})
this will crete an attribute called _id for the document of kasun.It is unique.Therefore don't set id attribute manually.
Related
I'm creating a Google Keeper replica where a user can log in and the list of todo list for that user is stored.
I'm new to mongoDB, express, and react, and I was wondering how someone would go about doing this. Would you create a User Schema with the "list objects" or create a User Schema and a separate List schema.
I think the creating one schema would be more efficient, but when I go to update or delete a note, I don't know how I would target a specific note without an ID since the ID would be associated with the entire user schema.
Thank you!
You can assign an unique id to the list entries while inserting them into the database. For example, you can use timestamp. The structure of your list items will be something like-
{ itemId: "1595488458403", value: "Do the laundry" }
As the items will be created one by one, therefore, there timestamps will be different. To create the timestamp of the present time, use-- new Date().getTime()
Here's the roadmap
Bring the value of the list item from your frontend to the backend. (say, "Do the laundry")
Define a variable "itemId" in the backend route:
itemId = new Date().getTime()
While inserting the item to the user's list of to-dos, insert:
{ itemId: itemId, value: "Do the laundry" }
I have a single collection into which I am inserting documents of different types. I use the type parameter to distinguish between different datatypes in the collection. When I am inserting a document, I have created an Id field for every document, but Cosmosdb has a built-in id field.
How can I insert a new document and retrieve the id of the created Document all in one query?
The CreateDocumentAsync method returns the created document so you should be able to get the document id.
Document created = await client.CreateDocumentAsync(collectionLink, order);
I think you just need to .getResource() method to get the create document obj.
Please refer to the java code:
DocumentClient documentClient = new DocumentClient(END_POINT,
MASTER_KEY, ConnectionPolicy.GetDefault(),
ConsistencyLevel.Session);
Document document = new Document();
document.set("name","aaa");
document = documentClient.createDocument("dbs/db/colls/coll",document,null,false).getResource();
System.out.println(document.toString());
//then do your business logic with the document.....
C# code:
Parent p = new Parent
{
FamilyName = "Andersen.1",
FirstName = "Andersen",
};
Document doc = client.CreateDocumentAsync("dbs/db/colls/coll",p,null).Result.Resource;
Console.WriteLine(doc);
Hope it helps you.
Sure, you could always fetch the id from creation method response in your favorite API as already shown in other answers. You may have reasons why you want to delegate key-assigning to DocumentDB, but to be frank, I don't see any good ones.
If inserted document would have no id set DocumentDB would generate a GUID for you. There wouldn't be any notable difference compared to simply generating a new GUID yourself and assign it into id-field before save. Self-assigning the identity would let you simplify your code a bit and also let you use the identity not only after persisting but also BEFORE. Which could simplify a lot of scenarios you may have or run into in future.
Also, note that you don't have to use GUIDs as as id and could use any unique value you already have. Since you mentioned you have and Id field (which by name, I assume to be a primary key) then you should consider reusing this instead introducing another set of keys.
Self-assigned non-Guid key is usually a better choice since it can be designed to match your data and application needs better than a GUID. For example, in addition to being just unique, it may also be a natural key, narrower, human-readable, ordered, etc.
I have a large array that comes in from an API that I'd like to store straight into MongoDB.
Model.create(largeArray) ... // many documents created
The problem is, I have one additional key:value pair that I need to set for all documents in that array. It's a user id, and many documents are created for a given user once per API call. So for a given Model.create call, the user id is the same for every doc in the array.
Without mapping over the array, is there an efficient way of adding a field with a consistent value? Something like Model.create(myLargeArray, {userId: someUserId}) would be ideal, but I know this isn't the case with the Mongoose API.
function addDocsForUser(largeArray, someUserId) {
// each element of largeArray needs to have `userId: someUserId` added to it
return Model.create(largeArray)
}
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.
Using Mongoose, I have a document that was previously pulled from the database, complete with an _id property, in raw Object format (IE, without all of the document methods, just straight from the db).
How can I use that data to create an instance of mongoose.Model without the system assigning the model a new _id? I want to then eventually save that model and have it update the existing document in the database.
Update: using a combination of #Jack Newcombe's method, and subsequently setting model.isNew to false, I get the following error: "Mod on _id not allowed". So now it knows to update, but Mongoose is not removing the _id field from the update request. There has to be one more system property on the Model that tells Mongoose whether or not to remove the _id during an update request. Any ideas?
I've figured it out, but I'm sure there is a better way. I'm surprised there isn't a way to do this easily with Mongoose's API.
Anyway, you need to the following:
Create the model like this: var model = new Model(data,
{_id:false});
Manually set model.isNew to false
Manually tell Mongoose that the _id field hasn't been modified, like this: delete model.$__.activePaths.states.modify._id
The reason I'm not so fond of this is because I'm taking advantage of the fact that JavaScript doesn't have true protected methods, and I'm basically hacking Mongoose in order to get it to work. So I'd love to hear other answers if anyone has.
You can prevent the schema for the model from automatically generating an _id by passing in an option that sets the _id to false:
var schema = new Schema({ name: String }, { _id: false });
Source: http://mongoosejs.com/docs/guide.html#_id