How to add custom ObjectId to parse-server object? - node.js

I have a problem when adding data to my User class by Mongoose that can't update it later by parse API.
I've found that's because of mongoose use ObjectId for _id field and parse just work with plain string as ObjectId.
The question is how can I set my custom unique plain string as ObjectId in Parse Server object creation?

You can do it like this:
const cryptoUtils = require('parse-server/lib/cryptoUtils');
const id = cryptoUtils.newObjectId();
Source: https://github.com/parse-community/parse-server/blob/master/src/cryptoUtils.js

Related

I need to be able to obtain only the string that makes up the Id in a query to MongoDB

I'm using mongoDB, mongoose and typescript and I need to keep the document ids when I query but I can only get the type _id: new ObjectId("62aa4bddae588fb13e8df552") . I only need to keep the string "62aa4bddae588fb13e8df552" to later store it and do other processing. I can't get rid of the new ObjectId
async findById(id:string) {
const convert = {"_id":id}
const userfindById = await userModel.findById(convert);
const iD = userfindById?._id
return userfindById;
}
ObjectId is just a type :
https://www.mongodb.com/docs/manual/reference/bson-types/#std-label-objectid
If you want to get the string you can extract with _id.toString(), if you want to store the string you should change the type of _id (or create a new property)

What is the difference between mongo ObjectID, ObjectId & Mongoose ObjectId

I can't figure out the difference between mongo ObjectID & ObjectId.
The document said ObjectId, but when I read the code, I see
import { ObjectID } from 'bson';
To make things even more confused is the mongoose document & code.
The mongoose also says ObjectId http://mongoosejs.com/docs/api.html#types-objectid-js. But when I read the codes I saw
// mongodb.ObjectID does not allow mongoose.Types.ObjectId(id). This is
// commonly used in mongoose and is found in an example in the docs:
// http://mongoosejs.com/docs/api.html#aggregate_Aggregate
// constructor exposes static methods of mongodb.ObjectID and ObjectId(id)
type ObjectIdConstructor = typeof mongodb.ObjectID & {
(s?: string | number): mongodb.ObjectID;
}
So what exactly is the difference between ObjectID, ObjectId and mongoose ObjectId?
I found there was another SO talking about this BSON::ObjectId vs Mongo::ObjectID
The links there were dead though and it didn't take about mongoose. So I hope my question won't be marked as duplicated.
Mongo ObjectID is a unique 12-byte identifier which can be generated by MongoDB as the primary key.
An ObjectID is a unique, not null integer field used to uniquely identify rows in tables
In Mongoose ObjectID is same as Mongo ObjectID and referencing an object in another collection

Manually deleting connect-mongo session by _id cast error

I'm attempting to manually delete a document from the connect-mongo sessions collection. When I try to delete a document I get the following error:
message: 'Cast to ObjectId failed for value "gl9-V-bjAjqv2Nwdf9vHPLN_Fnnl4Thz" at path "_id"'
express-session uses the following function to generate a session id:
function generateSessionId(sess) {
return uid(24);
}
The session generated from this function is making it way into the _id property of the sessions document. However when you try and find or delete the document by the generated id you get the error.
The mongodb docs say the _id should be
ObjectId is a 12-byte BSON type
ObjectId
I've tried to override the session id using the genid option on the session, but the override doesn't make it into the database.
How can I get a valid _id onto the document or query the document with an invalid _id?
Thanks!
My Infrastructure: Express 4.10, Node v0.12.7, Compose.io, connect-mongo, express-session
Okay so your problem here is the mongoose model you are using to delete documents from the session store. You probably should be calling req.session.destroy() or setting up TTL to remove expired sessions instead.
But basically, mongoose is expecting the "type" of the _id field to be an ObjectId and as such "autocasts". The mongo-connect middleware itself does not use mongoose methods, but talks to the underlying driver methods instead. So it does not have this problem when using it's internal methods.
Your mongoose schema definition should therefore look something like this:
var sessionSchema = new Schema({
"_id": String,
"session": String
},{ "_id" false });
Or at the very least contain { "_id": false } in order to remove the default autocasting behavior.

MongoDB: Can I use a created ObjectId before saving my document

Using mongoose on node.js:
Can I access the _id field on a model before it has been saved to the database and be sure that the ID will not change?
For example, I would like to do the following:
var model = new mongoose.model('MyModel');
someOtherObject.myModelId = String(model._id);
// Some more code...
model.save(...);
In Mongoose, _id values must always be assigned client-side as the docs indicate that:
Mongoose forces the db option forceServerObjectId false and cannot be overridden.
So the model._id value you get in the first line of your code will not be changed unless you do it in your own code before calling model.save.

How can I generate an ObjectId with mongoose?

I'd like to generate a MongoDB ObjectId with Mongoose. Is there a way to access the ObjectId constructor from Mongoose?
This question is about generating a new ObjectId from scratch. The generated ID is a brand new universally unique ID.
Another question asks about creating an ObjectId from an existing string representation. In this case, you already have a string representation of an ID—it may or may not be universally unique—and you are parsing it into an ObjectId.
You can find the ObjectId constructor on require('mongoose').Types. Here is an example:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();
id is a newly generated ObjectId.
Note: As Joshua Sherman points out, with Mongoose 6 you must prefix the call with new:
var id = new mongoose.Types.ObjectId();
You can read more about the Types object at Mongoose#Types documentation.
You can create a new MongoDB ObjectId like this using mongoose:
var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();
I needed to generate mongodb ids on client side.
After digging into the mongodb source code i found they generate ObjectIDs using npm bson lib.
If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson library :
const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2
Note: There is also an npm project named bson-objectid being even lighter
With ES6 syntax
import mongoose from "mongoose";
// Generate a new new ObjectId
const newId2 = new mongoose.Types.ObjectId();
// Convert string to ObjectId
const newId = new mongoose.Types.ObjectId('56cb91bdc3464f14678934ca');

Resources