Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use ObjectId as query condition in Node.js

Shulou Source: shulou.com Published: 2022-06-02 10:35:28 10月16日 Update

This article shows you how to use ObjectId in Node.js as a query condition, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Insert a piece of data into MongoDB

Insert a piece of data with the following structure in MongoDB:

{_ id: 5d6a32389c825e24106624e4, title: 'are there any interesting projects on GitHub', content: 'last month, a water friend asked me privately if there are any interesting items on GitHub that can be recommended? I said to him, "Yes, I'll clean it up in a couple of days." However, a month later, I forgot all about it and didn't remember 2_05.png until he reminded me yesterday. Creation: 2019-08-31T08:39:20.384Z}

Where the value "5d6a32389c825e24106624e4" of the above _ id is automatically assigned by MongoDB.

Use the ObjectId of MongoDB as the query condition

Note that the value "5d6a32389c825e24106624e4" of _ id is not a string, but an ObjectId object type. Therefore, the following query does not work:

/ / query specified document const findNews = function (db, newsId, callback) {/ / get collection const news = db.collection ('news'); / / query specified document news.findOne ({_ id: newsId}, function (err, result) {if (err) {console.error (' error end:'+ err.stack); return } console.log ("query the specified document, the response result is:"); console.log (result); callback (result);};}

The above newsId needs to be converted to the ObjectId object type. How do I do that? The reference for practice is as follows:

Const ObjectId = require ('mongodb'). ObjectId;// query specified document const findNews = function (db, newsId, callback) {/ / get collection const news = db.collection (' news'); / / query specified document news.findOne ({_ id: ObjectId (newsId)}, function (err, result) {if (err) {console.error ('error end:' + err.stack); return } console.log ("query the specified document, the response result is:"); console.log (result); callback (result);};}

Where require ('mongodb'). ObjectId is used to get the ObjectId class and convert the string newsId to the ObjectId type.

The above is how to use ObjectId as a query condition in Node.js. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Queries documents conditions types fun content characters strings objects skills data knowledge results projects concise concise things practices that is articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei MariaDB Apple Shulou Information OPPO Reno