Change uuid to integer id in mongodb - sails.js - mongodb

so I have switched the sails.js database from localdisk to mongodb server and all my ids changed to a uuid id.i found that normal id is much easier and cleaner. how can i change my ids to be integer ids again?
btw what are the benefits of using uuid? and how can i make an update request with that long id?
{
"name": "Matan",
"id": "544a7968101ca2903974cdc1",
"createdAt": "2014-10-24T16:08:08.052Z",
"updatedAt": "2014-10-24T16:08:08.052Z"
}

It's the "normal" way that MongoDB creates ids, is a combination of timestamp, machine identifier, process id and random values.
From MongoDB site: "Documents stored in a collection require a unique _id field that acts as a primary key. Because ObjectIds are small, most likely unique, and fast to generate"
It's not recommended to change the ids because is your primary key and maybe some other data is related to them.
If you want to have ids like 1,2,3,4,5... you have to setup your own generation and save the id when you create the model:
User.create({_id: 1, name: 'John'});
You can update the same way you do with "short" ids, through the blueprint api:
PUT /user/544a7968101ca2903974cdc1
And submit new the data with a form or via ajax.
Update a value on existing model example:
var postId;
// create a blog post for example
$.ajax({
url: '/post',
method: 'POST', // create a new entry in the db
data: {
title: 'Untitled Post',
text: 'Example blog post'
},
success: function(data){
// data = {id: 'randomGeneratedId', title: 'Untitled Post', text: 'Example blog post'}
postId = data.id;
}
});
// later...
$.ajax({
url: '/post/' + postId,
method: 'PUT', // update this post in the db
data: {
image: 'path/to/image.jpg'
},
success: function(data){
// data = {id: 'randomGeneratedId', image: 'path/to/image.jpg', title: 'Untitled Post', text: 'Example blog post'}
}
});

Related

Add a new field for already existing resource using PUT

I implemented google auth in my NextJS app. The idea is: user makes some progress working with my web app, I store this progress in local storage as an array. If he decides to register I receive the session back, then I send PUT request to db to update the document by inserting a new field (array) from local storage.
I implemented GET request that returns registered user data by email and it works. The question is, how to insert a new field using PUT method? In my case this field is array and calls progress. I'm not sure if I should use update.
This is the record from my mongodb:
_id: 63cc85641624a77f17ca5f29
name: "John P"
email: "john.p#gmail.com"
image: "https://lh3.googleusercontent.com/a/AEdFTp7xzF4eYtyhTgRxmgP4vYdCqDa6zW…"
emailVerified: null
I want to add a new field: progress: ['some data']
This is my PUT request:
case 'PUT':
const updateData = await fetch(`${baseUrl}/updateOne`, {
...fetchOptions,
body: JSON.stringify({
...fetchBody,
filter: { email: email },
update: {} <---------------!!!!!
}),
})
const updateDataJson = await updateData.json()
res.status(200).json(updateDataJson.documents)
break
If you want to update your document using updateOne, and add a progress key, you can use:
filter: { email: email },
update: {$set: {progress: arr}}

Why I have more documents in my MongoDB collection than I created

I'm creating a chat app using MERN and when I inserted a new user in my collection I got all the collection
await usersCollection.find();
and this array included not only my users:
{
_id: new ObjectId("63582710bc6f137c8532ceda"),
username: 'Пользователь 1',
img: '...long img string',
userId: 'dfy5nOU972SxsD7EB3q4ka7Z_9ZzA_LN'
},
but a lot of documents looking like this:
{
_id: new ObjectId("6358205ce63a49c2ed4b8575"),
type: 2,
uid: 'ac98be53ee7cb872',
nsp: '/'
}
And when I create 1 new user I get various number of these new objects.
I can look only for documents with fields I need:
await usersCollection.find({}, { username: 1, img: 1, userId: 1 });
But it doesn't solve my problem, these objects will be created in my collection anyway
My full code is here: https://codepen.io/yuliya-d98/pen/mdKdKrM?editors=0010
Update: according to MongoDB triggers they are creating every 5 seconds and not depending on requests.
Update 2: these objects create in every socket.io heartbeat. And if I delete mongoDB-socket.io adapters, these objects don't create.

Mongoose subdocuments return different ID every time

I have a model Franchise that has another Schema Employee as its subdocuments for a field. The structure is as follows.
Franchise.js
const Franchise = new mongoose.Schema(
{
franchiseName: String,
address: String,
managers: [Employee]
});
export default mongoose.model(
"Franchise",
Franchise
);
Employee.js
const Employee = new mongoose.Schema(
{
name: String,
email: String,
phoneNo: Number,
password: String,
});
export default Employee;
The issue I am facing is with every query to Franchise, it returns a new _id for the objects in managers field. Is there any way to make it constant ?
For instance, I am running a simple findById on Franchise and store it in franchise variable.
and then I console.log(franchise.managers).
It prints different IDs each time the query is run.
[
{
_id: new ObjectId("61925d2697852574eb0ba9ab"),
name: 'Franchise Manager 1',
email: 'franchise1#sfc.com',
phoneNo: 1234567890,
}
]
Second time the query is run:
[
{
_id: new ObjectId("61925ba8130aca93a7dd3dbc"),
name: 'Franchise Manager 1',
email: 'franchise1#sfc.com',
phoneNo: 1234567890
}
]
As you can see, the employee is the same, however it has different Id for each call. Kindly help.
Thanks.
Alright, I figured it out. The issue is that there was no _id stored in the database for existing data of managers. The Employee schema was added later on, so as the _id was not present in the database only, a new one was being generated each time.

MongoDB joining user and likes collection based on reference ids

I am trying to create a little social network using ExpressJS and MongoDB. I have a little problem relating to likes and posts collection. I know you can embed a likes inside a posts collection, but I have decided to separate both of the collection and use reference ids so I can join them later on. The main problem I have currently is this, how do I include the likes reference on the posts collection?
Let's say my posts schema looks something like this:
const PostSchema = new Schema({
content: { type: String, required: true },
isLiked: false,
}, { timestamps: true });
and my likes schema looks something like this:
const LikeSchema = new Schema(
{
// The user who is liking the post.
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
// The post that is being liked.
question: {
type: Schema.Types.ObjectId,
ref: 'Question',
required: true
},
},
{ timestamps: true }
);
I wanna make it so that whenever I try to query the posts collection, I can also get the likes embedded in it by referencing the collection and not modifying the schema to have embedded likes in it.
An example response:
{
_id: ObjectId("test"),
content: 'A post',
isLiked: false,
likes: ["A user object here based on the `likes collection`"]
}
You have to obtain them before sending the response:
Find all the likes of that post, something similar to Like.find({ question: <postId> })
Then you can resolve the users of that likes, in the command above you can concatenate .populate('user') with the mongoose populate feature
If you are interested only to the user object and not the entire like object, you can extract resolved user: const users = likes.map(x => x.user)
Then you can add the users array to the post object and sending the final object as response

Unable to get the id of newly created record sails js

I am creating a new record like this:
Resource.create({
title: req.body.title,
address: {...req.body.address},
email: req.body.email,
}, (err, record) =>{
if(err){
res.send({'status': err});
}else{
res.send(
{
'status': 'it worked',
'data': req.body
}
);
sails.log(record.title)
}
});
The request process perfectly and the new record is added to the database(I can see it too). But I cant get the id right when its created for some weird reason.
I've been following a tutorial and record is supposed to not be undefined, I am using MongoDB with SailsJS
You have to chain a "fetch" after creating the record, for example:
let resource = Resource.create({...}).fetch();
This will fetch the record you just created with its associated id.