mongodb 없이 _id 문자열과 같은 mongodb를 만들 수 있는 방법이 있습니까?
mongodb에서 생성한 _ids의 포맷이 정말 마음에 듭니다.주로 클라이언트 쪽에서 날짜와 같은 데이터를 가져올 수 있기 때문입니다.저는 다른 데이터베이스를 사용할 계획이지만 여전히 제 문서에 해당 유형의 _id를 원합니다.mongodb를 사용하지 않고 어떻게 이러한 ID를 만들 수 있습니까?
감사합니다!
클라이언트에서 공식 MongoDB BSON lib 사용
다음을 생성하는 브라우저 클라이언트가 있습니다.ObjectId저는 제가 같은 직원을 고용하고 있는지 확인하고 싶었습니다.ObjectId클라이언트에서 서버에서 사용되는 알고리즘입니다.MongoDB에는 이를 달성하는 데 사용할 수 있는 js-bson이 있습니다.
자바스크립트를 노드와 함께 사용하는 경우.
npm install --save bson
require 문 사용
var ObjectID = require('bson').ObjectID;
var id = new ObjectID();
console.log(id.toString());
ES6 가져오기 문 사용
import { ObjectID } from 'bson';
const id = new ObjectID();
console.log(id.toString());
라이브러리에서는 오래된 좋은 스크립트 태그를 사용하여 가져올 수도 있지만 저는 이것을 시도하지 않았습니다.
Javascript의 매우 쉬운 유사 ObjectId 생성기:
const ObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).toString(h)) =>
s(d.now() / 1000) + ' '.repeat(h).replace(/./g, () => s(m.random() * h))
객체 ID는 일반적으로 클라이언트에 의해 생성되므로 MongoDB 드라이버는 객체 ID를 생성하기 위한 코드를 가집니다.
JavaScript를 찾고 있는 경우 MongoDB Node.js 드라이버의 일부 코드가 있습니다.
https://github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js
그리고 또 다른 더 간단한 솔루션:
https://github.com/justaprogrammer/ObjectId.js
Rubin Stolk와 Chris V의 답변을 더 읽기 쉬운 구문(KISS)으로 확장.
function objectId () {
return hex(Date.now() / 1000) +
' '.repeat(16).replace(/./g, () => hex(Math.random() * 16))
}
function hex (value) {
return Math.floor(value).toString(16)
}
export default objectId
루벤스톨크의 대답은 훌륭하지만, 의도적으로 불투명한가요?다음과 같이 매우 쉽게 구분할 수 있습니다.
const ObjectId = (rnd = r16 => Math.floor(r16).toString(16)) =>
rnd(Date.now()/1000) + ' '.repeat(16).replace(/./g, () => rnd(Math.random()*16));
(약간 더 적은 문자로 표시됨).그래도 칭찬해요!
이것은 새로운 객체를 생성하기 위한 간단한 함수입니다.이드
newObjectId() {
const timestamp = Math.floor(new Date().getTime() / 1000).toString(16);
const objectId = timestamp + 'xxxxxxxxxxxxxxxx'.replace(/[x]/g, () => {
return Math.floor(Math.random() * 16).toString(16);
}).toLowerCase();
return objectId;
}
https://www.npmjs.com/package/mongo-object-reader 16진수 문자열을 읽고 쓸 수 있습니다.
const { createObjectID, readObjectID,isValidObjectID } = require('mongo-object-reader'); //Creates a new immutable `ObjectID` instance based on the current system time. const ObjectID = createObjectID() //a valid 24 character `ObjectID` hex string. //returns boolean // input - a valid 24 character `ObjectID` hex string. const isValid = isValidObjectID(ObjectID) //returns an object with data // input - a valid 24 character `ObjectID` hex string. const objectData = readObjectID(ObjectID) console.log(ObjectID) //ObjectID console.log(isValid) // true console.log(objectData) /* { ObjectID: '5e92d4be2ced3f58d92187f5', timeStamp: { hex: '5e92d4be', value: 1586681022, createDate: 1970-01-19T08:44:41.022Z }, random: { hex: '2ced3f58d9', value: 192958912729 }, incrementValue: { hex: '2187f5', value: 2197493 } } */
여기에 자세한 사양이 있습니다.
http://www.mongodb.org/display/DOCS/Object+IDs
자신의 ID 문자열을 롤링하는 데 사용할 수 있습니다.
언급URL : https://stackoverflow.com/questions/10593337/is-there-any-way-to-create-mongodb-like-id-strings-without-mongodb
'programing' 카테고리의 다른 글
| 'git merge'와 'gitrebase'의 차이점은 무엇입니까? (0) | 2023.05.24 |
|---|---|
| Entity Framework 4.1 코드 먼저 클래스 속성 무시 (0) | 2023.05.24 |
| 스위프트 레퍼런스의 _ 밑줄 대표자는 무엇입니까? (0) | 2023.05.24 |
| $lookup을 사용한 MongoDB 집계는 쿼리에서 반환할 일부 필드만 포함(또는 프로젝트)합니다. (0) | 2023.05.24 |
| vba 코드 리팩터링 - 도움이 되는 도구가 있습니까? (0) | 2023.05.24 |