'How to generate an id when adding an object in node.js
I am trying to append an id to an object if it's the first and if there are others I want to add +1 to one that I am adding.
I am using function that is called save and inside it there is a writeFile and an appendFile method:
class Contenedor {
constructor (nombre){
this.nombre= nombre
this.count = 0
this.product = []
}
save(obj) {
if (this.count <= 1){
fs.writeFile(`./${this.nombre}`, JSON.stringify(obj), 'utf-8', (err)=> {
if (err) {
console.log("Error al crear archivo")
} else {
this.product.map(x=>{
x['id'] = this.count;
this.count++
})
console.log("Archivo creado")
}
})
} else {
fs.appendFile(`./${this.nombre}`, JSON.stringify(obj), 'utf-8', (err)=> {
if (err) {
console.log("Error al crear archivo")
} else {
this.product.map(x=>{
x['id'] = this.count;
this.count++
})
console.log("Archivo agregado")
}
})
}
}
}
let archivos = new Contenedor('text.json')
archivos.save(
[
{
title: 'Escuadra',
price: 152.50,
thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.seawhite.co.uk%2Fimagecache%2F6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
}
]
I want to have a unique id for the objects. I'm using map() method and already tried this.count++.
Anyone knows how to do it?
Solution 1:[1]
const fs = require('fs');
class Contenedor {
constructor(nombre) {
this.nombre = nombre
this.count = 0
this.product = []
this.writelock = false;
fs.writeFileSync(`./${this.nombre}`, '[');
}
save(obj) {
if (this.writelock) {
console.log('waiting for a sec');
setTimeout(() => this.save(obj), 1000);
} else {
console.log('started writing', this.count);
this.writelock = true;
obj['id'] = this.count;
let toWrite = JSON.stringify(obj, null, 2);
if (this.count > 0) toWrite = ', ' + toWrite;
fs.appendFile(`./${this.nombre}`, toWrite, 'utf-8', (err) => {
if (err) {
console.log("Error al crear archivo")
} else {
this.product.push(obj);
this.count++;
console.log("Archivo agregado");
}
this.writelock = false;
})
}
}
done() {
if (this.writelock) {
console.log('waiting for a sec');
setTimeout(() => this.done(), 1000);
} else {
this.writelock = true;
fs.appendFileSync(`./${this.nombre}`, ']', 'utf-8', (err) => {
if (err) {
console.log("Error al crear archivo")
}
this.writelock = false;
})
}
}
}
let archivos = new Contenedor('text.json')
archivos.save(
{
title: 'Escuadra',
price: 152.50,
thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.seawhite.co.uk%2Fimagecache%2F6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
}
)
archivos.save(
{
title: 'Escuadra',
price: 100.50,
thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.seawhite.co.uk%2Fimagecache%2F6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
}
)
archivos.save(
{
title: 'Escuadra',
price: 126.50,
thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.seawhite.co.uk%2Fimagecache%2F6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
}
)
archivos.done();
Added a write-lock in case save is used multiple times. You can remove that if you are going to add everything in one save only. Added '[' at the start and ']' at end of the JSON file to have a valid JSON file.
Solution 2:[2]
Instead of reinventing the wheel and complicating things, just go simple. Use an randomUUID() for you unique id:
const { randomUUID } = require('crypto');
myObject.id = randomUUID();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gyan roy |
| Solution 2 | Jone Polvora |
