Querying a MongoDB based on Mongo ID in a node.js app

后端 未结 5 1158
夕颜
夕颜 2020-12-10 02:57

I\'m using a node.js and mongodb, and I\'m trying to query the database based on the mongo generated ID using the following:

    collection.findOne( {_id:doc         


        
5条回答
  •  Happy的楠姐
    2020-12-10 03:43

    First we need to get ObjectID from mongodb library and need to create new instance in following way., so that you will get the ObjectID of string. If your are using es6 in your code this code

    import { ObjectID } from 'mongodb';
    
    var emQuery = [
              {
                $match: {
                  _id: new ObjectID(tlvaltResult[0].customers.createdBy)
                }
              },
              {
                $project: {
                  _id:1,
                  emailId:1,
                  mobile:1
                }
              }
            ];
    
    console.log(emQuery,'emQuery');
    
    [ { '$match': { _id: 5ad83ff0b443435298741d3b } },
      { '$project': { _id: 1, emailId: 1, mobile: 1 } } ] 
    
    var emResult = await User.getAggregation(emQuery);
    
    console.log(emResult,'emResult');
    
    [ { _id: 5ad83ff0b443435298741d3b,
        emailId: 'superAdmin@limitlessmobile.com' } ]
    

提交回复
热议问题