如何在nodejs mongodb本机驱动程序中将字符串转换为ObjectId? [英] How to convert a string to ObjectId in nodejs mongodb native driver?

查看:569
本文介绍了如何在nodejs mongodb本机驱动程序中将字符串转换为ObjectId?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在中使用 mongodb原生驱动程序 nodejs 环境,我需要将 id 字符串转换为 ObjectId 在我的更新查询中使用它,我该怎么做?

I'm using mongodb native driver in a nodejs environment and I need to convert an id string to ObjectId to use it in my update query, how can I do this?

推荐答案

使用 ObjectId nodejs driver doc

如果您有一个代表BSON ObjectId的字符串(例如从Web请求收到),那么您需要将其转换为ObjectId实例:

When you have a string representing a BSON ObjectId (received from a web request for example), then you need to convert it to an ObjectId instance:

const {ObjectId} = require('mongodb'); // or ObjectID 
// or var ObjectId = require('mongodb').ObjectId if node version < 6

const updateStuff = (id, doc) => {
  // `ObjectId` can throw https://github.com/mongodb/js-bson/blob/0.5/lib/bson/objectid.js#L22-L51, it's better anyway to sanitize the string first
  if (!ObjectId.isValid(s)) {
    return Promise.reject(new TypeError(`Invalid id: ${id}`));
  }
  return collection.findOneAndUpdate(
    {_id: ObjectId(id)}, 
    {$set: doc}, 
    {returnOriginal: false}
  );
};

这篇关于如何在nodejs mongodb本机驱动程序中将字符串转换为ObjectId?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆