[mongodb] Node.js Mongoose.js string to ObjectId function

Is there a function to turn a string into an objectId in node using mongoose? The schema specifies that something is an ObjectId, but when it is saved from a string, mongo tells me it is still just a string. The _id of the object, for instance, is displayed as objectId("blah").

This question is related to mongodb node.js mongoose

The answer is


You can do it like so:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');

Judging from the comments, you are looking for:

mongoose.mongo.BSONPure.ObjectID.isValid

Or

mongoose.Types.ObjectId.isValid

You can do it like this:

var mongoose = require('mongoose');
var _id = mongoose.mongo.BSONPure.ObjectID.fromHexString("4eb6e7e7e9b7f4194e000001");

EDIT: New standard has fromHexString rather than fromString


var mongoose = require('mongoose');
var _id = mongoose.mongo.ObjectId("4eb6e7e7e9b7f4194e000001");

You can use this also

const { ObjectId } = require('mongodb');
const _id = ObjectId("4eb6e7e7e9b7f4194e000001");

it's simplest way to do it


Just see the below code snippet if you are implementing a REST API through express and mongoose. (Example for ADD)

_x000D_
_x000D_
...._x000D_
exports.AddSomething = (req,res,next) =>{_x000D_
  const newSomething = new SomeEntity({_x000D_
 _id:new mongoose.Types.ObjectId(), //its very own ID_x000D_
  somethingName:req.body.somethingName,_x000D_
  theForeignKey: mongoose.Types.ObjectId(req.body.theForeignKey)// if you want to pass an object ID_x000D_
})_x000D_
}_x000D_
...
_x000D_
_x000D_
_x000D_

Hope it Helps


I couldn't resolve this method (admittedly I didn't search for long)

mongoose.mongo.BSONPure.ObjectID.fromHexString

If your schema expects the property to be of type ObjectId, the conversion is implicit, at least this seems to be the case in 4.7.8.

You could use something like this however, which gives a bit more flex:

function toObjectId(ids) {

    if (ids.constructor === Array) {
        return ids.map(mongoose.Types.ObjectId);
    }

    return mongoose.Types.ObjectId(ids);
}

Examples related to mongodb

Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Failed to start mongod.service: Unit mongod.service not found db.collection is not a function when using MongoClient v3.0 MongoError: connect ECONNREFUSED 127.0.0.1:27017 MongoDB: How To Delete All Records Of A Collection in MongoDB Shell? How to resolve Nodejs: Error: ENOENT: no such file or directory How to create a DB for MongoDB container on start up?

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to mongoose

Querying date field in MongoDB with Mongoose Server Discovery And Monitoring engine is deprecated Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true Mongodb: failed to connect to server on first connect Push items into mongo array via mongoose Mongoose: findOneAndUpdate doesn't return updated document mongoError: Topology was destroyed Difference between MongoDB and Mongoose How can you remove all documents from a collection with Mongoose? E11000 duplicate key error index in mongodb mongoose