0

I had JSON that contain JSON string . I want to replace JSON string to ObjectId

{
"_id" : "5fd484c39590020dc0dfb82a",
"eventId" : "5fd210952f4961e258437c9f"
}

I want to get the ObjectId like so,

{
"_id" : ObjectId("5fd484c39590020dc0dfb82a"),
  "eventId" : ObjectId("5fd210952f4961e258437c9f")
}
db.collection('members').find().toArray({
"_id" : ObjectId("5fd484c39590020dc0dfb82a"),
  "eventId" : ObjectId("5fd210952f4961e258437c9f")
})

Is possible to convert the JSON string to ObjectId

1
  • But you are converting it to ObjectId in your last code block, are you not? Commented Jan 13, 2021 at 10:14

2 Answers 2

1

Assuming that you might use mongoose, you can do it simply like that:

const mongoose = require('mongoose');
const _id = mongoose.Types.ObjectId(object._id);
const eventId = mongoose.Types.ObjectId(object.eventId);

If you are not using mongoose, an easier way would be to do this:

const { ObjectId } = require('mongodb');
const _id = ObjectId(object._id);
const eventId = ObjectId(object.eventId);

Please note that object would be this:

const object = {
   "_id" : "5fd484c39590020dc0dfb82a",
   "eventId" : "5fd210952f4961e258437c9f" 
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should do the following :

const mongoose = require('mongoose');
var ObjectId = require('mongodb').ObjectId;

member = mongoose.Types.ObjectId('pass your string here');
console.log(user, typeof(member));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.