简体   繁体   中英

node.js/mongoDB - How to manage ObjectIDs between clients and web-server

Using Node.js 4.2.4 and mongoDB 3.2

Separation of Concerns - Keeping Clients Decoupled from mongoDB

Problem:

I'm use to the idea of sending out ids as strings from the server and reading them back as strings from the client - but with mongoDB's use of ObjectIDs I'm getting confused because logically it seems that - to keep the clients decoupled from the database - there will need to be casting done on ObjectIDs and there string counterparts as they are shuttled back and forth between the client and the server.

Clarifying Questions:

1) As data is shipped out the client I am assuming it's common to use ObjectIDs to map UI interactions to the data(eg user clicks a post). When doing so, do I need to cast ObjectIDs to strings as they go client side and cast them back to ObjectIDs as they go back to the server side?

2) Should ALL key generation and casting(if needed) should all be happening server-side? (either coupled with node server or a layer between the database and the web-server)

1) Yes.

2) Yes.

An ObjectId can be cast to string for transport (usually JSON) and back to an ObjectId when you need to query the database. The client only has to know it's some arbitrary string representing an object.

Using npm bson-util could be a proper way to send bson data to the client. Also you can parse the data in client as bson again.

 import {parse, stringify} from 'bson-util'; let a = {b: new ObjectID()}; stringify(a); // {"b":{"$oid":"5e32849068f40e424a80fe42"}} parse('{"b":{"$oid":"5e32849068f40e424a80fe42"}}'); // {b: ObjectID("5e32849068f40e424a80fe42")}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM