Home > Software design >  How to convert from new ObjectId() to string in Mongodb?
How to convert from new ObjectId() to string in Mongodb?

Time:10-28

Below is my code to create a review and add it to my reviews array of restaurants collections, I am also displaying this review after adding it to the collection.

const res = require('./restaurants');
async create (restaurantId, title, reviewer, rating, dateOfReview, review) {

    
   // check(restaurantId, title, reviewer, rating, dateOfReview, review)
    restaurantId = ObjectId(restaurantId)
    const restaurantsCollection = await restaurants();
    let newReview = {
      _id: ObjectId(),
      title : title,
      reviewer : reviewer,
      rating : rating,
      dateOfReview : dateOfReview,
      review : review
    };
    
    
  
    await restaurantsCollection.updateOne({ _id : restaurantId},{ $push: {reviews: newReview} })
   
    const r = await restaurantsCollection.findOne({ _id: restaurantId });
    let len = r.reviews.length
  
    r.overallRating  = rating
 
    let avg = r.overallRating/len
    
    /* await restaurantsCollection.updateOne(
      { "r.overallRating": r.overallRating },
      { $set: { "r.$.overallRating" : avg } }
   )  */
   var query = { _id : restaurantId };
   var data = { $set : {overallRating : avg} } ;
   await restaurantsCollection.updateOne(
     query,data
   );
 
   restaurantId = restaurantId.toString().replace(/ObjectId\("(.*)"\)/, "$1");
    return res.get(restaurantId)
    
   
  },

restaurant.js:

async get(id) {
    if (!id) throw 'You must provide an id to search for';
    checkString(id);
    var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
    if(checkForHexRegExp.test(id)===false) throw 'Not a valid objectid';
    id = ObjectId(id);
    const restaurantsCollection = await restaurants();
    const res= await restaurantsCollection.findOne({ _id: id });
    if (res === null) throw 'No restaurant with that id';
    res._id = res._id.toString().replace(/ObjectId\("(.*)"\)/, "$1");
    return res;
  },

The output I get is:

{
  _id: '6174cf81053daf4b9937ef80',
  name: 'Saffron Lounge',
  location: 'SoHo, New York',
  phoneNumber: '123-456-1234',
  website: 'http://www.thesaffronlounge.com',
  priceRange: '$$$',
  cuisines: [ 'Italian' ],
  overallRating: 0.13518518518518519,
  serviceOptions: { dineIn: false, takeOut: false, delivery: true },
  reviews: [
    {
      _id: new ObjectId("6174cfb953edbe9dc5054f9a"),
      title: 'bo',
      reviewer: 'dd',
      rating: 2,
      dateOfReview: '15/1/2002',
      review: ' ruh'
    },

How can I change the _id field to not have the new ObjectID and just display the string, I tried to add JSON.stringify() to the returning result but it does not return it as an object, also I tried to use:

toString().replace(/ObjectId\("(.*)"\)/, "$1");

But it does not work for the reviews as I am creating a new Object() in the create function and I don't know where to add this correctly, is there an easier way around to display:

_id: "6174cfb953edbe9dc5054f9a"

CodePudding user response:

You just need to require the ObjectId function from your mongo.

ObjectId = require('mongodb').ObjectID;

Then you can use it like that:

ObjectId("34234234234234234234")

CodePudding user response:

Adding the below code worked for me:

for(i=0;i<a.reviews.length;i  ){
         a.reviews[i]._id = a.reviews[i]._id.toString().replace(/ObjectId\("(.*)"\)/, "$1");
       } 
  • Related