If I define a model in mongoose, and create a document using something like the code below:
const Model = require("./Model")
const newModelItem = new Model({
...data
})
await newModelItem.save()
I noticed that there is an ID field immediately available in the newModelItem object.
How does MongoDB ensure that the key isn't a duplicate?
Actually that's MongoDB's work to generate (automatically) unique 12-bytes / 24 hex digits IDs. Please have a look at its structure and how it is being created:
Source: MongoDB ObjectId generation
Related
When adding a field called date in mongo db, I can do just:
date: {
type: Date,
default: Date.now
}
and it will automatically add date field to my new collection when it was created. Is there some way to add a self-incrementing index (id) to my collections?
Note: I tried to do it on client side, however with every time I push collection with (id) field, its being deleted from the collection and replaced with _id which is a long string with random characters. Way to long!
Looking for every hints.
Edit: code responsible for adding use to db
app.post("/users", function (req, res) {
createUser(req.body, function (err, user) {
if (err) {
return res.json(err);
}
return res.json(user);
});
});
MongoDB automatically makes unique ids for each object in the database, resulting in each entry having a unique _id field being an ObjectId. You don't really need to worry about specifying custom ids.
You can sort by _id if you want objects roughly in the order they were created, or you could add a date field which is set on creation and sort by that.
Other than that, I'm not sure what you'd gain by having auto incrementing ids
There are multiple ways to implement an auto-increment index but it is not considered a good practice.
Detailed information here: Auto increment in MongoDB to store sequence of Unique User ID
Check Rizwan Siddiquee answer about how to implement it with a stored javascript function.
Another way would be to implement it on application layer using any kind of ODM but this is obviously dangerous and not so trustable for serious applications.
I'm using Firebase and Vuejs to create an database element, which has object array inside.
That's how the field looks, and I want to add tasks through the form into the 'moreTasks' as an array.
I tried using this, but it just creates new entity in the database.
db.collection('Tasks').add({
tasker: this.tasker.taskerName
})
I also tried checking API but I couldnt understand the refs, because I was using different methods to achieve that goal.
creatTask() {
db.collection('Tasks').add({
task_id: this.task_id,
name: this.name,
What would be correct way to approach this problem?
You can append an item to an array using FieldValue.arrayUnion() as described in the documentation. For example:
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});
The accepted answer used to be correct but is now wrong. Now there is an atomic append operation using the arrayUnion method:
https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
This is true as long as you are using firestore and not real time db (which I assume is the case from the tags)
I update 100's of documents every second by pushing new data to an array in its document. To get the document of which I am going to add data to, I use the mongoose .find().limit(1) function, and return the whole document. It works fine.
To help with some memory and cpu issues I have, I was wondering how I could get find() to only return the id of the document so I can use that to $push or $set new data.
Thanks.
You want to use Projection to tell your query exactly what you want off of your objects.
_id is always included unless you tell it not to.
readings = await collection
.find({
name: "Some name you want"
})
.project({
_id: 1 // By default
})
.toArray();
You could use the distinct method in order to get an array of _id for your query.
Follow this question
As mentioned by #alexmac, this works for me:
collection.find({}, '_id')
I have a big JSON string that is 10 records, each with their own properties. I need to ingest them into my MongoDB with Javascript. I'm basically useless with Javascript, and google has largely failed me. The JSON looks like this, basically:
[{"ID":1,"Name":"bob"},{"ID":2,"Name":"Jim"}]
Obviously a lot more, but that's the basic structure. How would one, using Node.js for example, import that into Mongo? Mongo's documentation largely only covers their shell commands, but those dont' directly translate into Javascript.
You could do a bulk insert like so:
var MyObject = mongoose.model('MyObject', MyObjectSchema);
var objectsArray = [/* array of MyObject objects */];
MyObject.collection.insert(objectsArray, callback);
Well i normally use mongoose plugin driver, to save such a document , define the schema first, at a glance your schema seems to have two fields ID and Name, with id custom. It is custom because mongodb uses it own id, to change this use auto-increment-plugin. So after you define your schema, mongodb will only save or insert a object if the fields match the schema.
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
The above is the format for a document insertion.document document or array A document or array of documents to insert into the collection.
Hope this helps.
I'm working with node.js and mongoose. I'm creating a REST API to expose my User model:
var userSchema = new Schema({
_id: {type:Number},
username: {type:String},
age: {type:Number},
genre:{type: Number,ref:'Genre'},
country: {type: Number,ref:'Country'}
});
As you can see I decided to include an _id field, so if I want to create a new user I'll need to generate the value for this field, for example:
exports.createUser = function(req,res){
var user = new User({
_id: //Generate and assing value here
//Other properties are retrieved from the request object
});
};
How could I "generate" or assign a value to my _id field properly? How does mongo deals with this?
I never used mongoose. but if _id is not included in insert query, mongodb driver will generate _ids for you as an ObjectId object. and if you wish to use your own _ids, it's up to you to decide about its type and length, and also you have to guarantee its uniqueness among the collection because any attempt to insert a document with a duplicated _id will fail.
accepted answer of this question may be useful, if you are looking for a method for creating custom _ids that provides a decent degree of guaranteed uniqueness.
mongoDB requires that _id, if supplied, be unique. If _id is not supplied, it is created by the client-side driver (i.e. NOT the mongod server!) as a 12-byte BSON ObjectId with the following structure:
4-byte value representing the seconds since the Unix epoch,
3-byte machine identifier,
2-byte process id, and
3-byte counter, starting with a random value.
more info available here: http://docs.mongodb.org/manual/reference/object-id