简体   繁体   中英

How to convert a string to a mongodb ObjectId?

I am successfully able to insert the following in mongo db as a string. But I want it to be inserted as an objectId.

parentId": "5ced2388dbbbe124d8671067"

This is the parentId in string format.

How can I convert it to objectId format?

Mongodb 4.0 has introduced $toObjectId aggregation to convert string value to an ObjectId. here's an example

db.getCollection('foo_collection').aggregate([
  { "$addFields": {
    "bar" :  { "$toObjectId": "$bar_id" }
  }},
  { "$out": "new_foo_collection" }
])

Here's the link

you must use mongoose like that

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('5ced2388dbbbe124d8671067');

You can use mongoose :

const mongoose = require('mongoose');
let yourId = mongoose.Types.ObjectId('5ced2388dbbbe124d8671067');

It will return type ObjectId variable .

in case of typescript:

import mongoose from "mongoose"; // will work
import * as mongoose from "mongoose"; // won't work

then

const objectId = mongoose.Types.ObjectId(id);

Happy Coding.

const ObjectId = require('mongodb').ObjectID
parentId =  "5ced2388dbbbe124d8671067"
let data = new ObjectId(parentId)
console.log(typeof(data))
console.log(typeof(parentId))

It can be done by writing two lines of code to save it as a object id

let ObjectId = require('mongodb').ObjectID;
parentID = ObjectId("5ced2388dbbbe124d8671067")

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