【问题标题】:How to convert from new ObjectId() to string in Mongodb?如何在 Mongodb 中从 new ObjectId() 转换为字符串?
【发布时间】:2021-10-28 09:07:56
【问题描述】:

下面是我创建评论并将其添加到我的餐馆集合评论数组中的代码,我也在将它添加到集合后显示此评论。

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;
  },

我得到的输出是:

{
  _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'
    },

如何将 _id 字段更改为没有新的 ObjectID 并仅显示字符串,我尝试将 JSON.stringify() 添加到返回结果中,但它没有将其作为对象返回,我也尝试使用:

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

但它不适用于评论,因为我在 create 函数中创建了一个新的 Object() 并且我不知道在哪里正确添加它,有没有更简单的方法来显示:

_id: "6174cfb953edbe9dc5054f9a"

【问题讨论】:

    标签: node.js mongodb objectid


    【解决方案1】:

    您只需要从您的 mongo 中获取 ObjectId 函数。

    ObjectId = require('mongodb').ObjectID;
    

    那么你可以这样使用它:

    ObjectId("34234234234234234234")
    

    【讨论】:

    • 我在哪里显示这个,因为评论不是一个集合,我从餐馆集合返回数据
    • 我也试过了,没用:await restaurantCollection.updateOne({ _id : ObjectId(restaurantId).toString()},{ $push: {reviews: newReview} })
    【解决方案2】:

    添加以下代码对我有用:

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

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2011-12-11
      • 2018-11-09
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2014-04-20
      • 1970-01-01
      • 2014-12-08
      相关资源
      最近更新 更多