Node.js use of MongoDB ObjectId as a query

When inserting data into a MongoDB in ObjectId automatically generated data as the primary key.
So how do the only query data through ObjectId it?

An insert data in MongoDB

An insert data in MongoDB the structure:

{
  _id: 5d6a32389c825e24106624e4,
  title: 'GitHub 上有什么好玩的项目',
  content: '上个月有水友私信问我,GitHub 上有没有比较好玩的项目可以推荐?我跟他说:"有,过两天我整理一下"。\n' +
    '\n' +
    '然而,一个月过去了,我把这件事情忘了精光,直至他昨天提醒我才记起2_05.png。\n',
  creation: 2019-08-31T08:39:20.384Z
}

Wherein the value of _id "5d6a32389c825e24106624e4", is automatically assigned MongoDB.

Use of MongoDB ObjectId as a query

Notice, the value of the _id "5d6a32389c825e24106624e4" is not a string, but ObjectId object type. Therefore, the following query will not work:

// 查询指定文档
const findNews = function (db, newsId, callback) {
    // 获取集合
    const news = db.collection('news');

    // 查询指定文档
    news.findOne({_id: newsId},function (err, result) {
        if (err) {
            console.error('error end: ' + err.stack);
            return;
        }
        
        console.log("查询指定文档,响应结果是:");
        console.log(result);
        callback(result);
    });
}

Need to be converted to the above newsId ObjectId object type. How to do it? Refer to the following practices:

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

// 查询指定文档
const findNews = function (db, newsId, callback) {
    // 获取集合
    const news = db.collection('news');

    // 查询指定文档
    news.findOne({_id: ObjectId(newsId)},function (err, result) {
        if (err) {
            console.error('error end: ' + err.stack);
            return;
        }
        
        console.log("查询指定文档,响应结果是:");
        console.log(result);
        callback(result);
    });
}

Wherein, require('mongodb').ObjectIdfor obtaining ObjectId class and into the string newsId ObjectId type.

References

Guess you like

Origin yq.aliyun.com/articles/716673