简体   繁体   中英

Using objectid can't retrieve data from MongoDB in Node.js

When I pass objectid of 1 hospital from Postman to this program it returns only empty array . But there is one data matching that objectid . Can you help me solve this? When I try to debug the program in console, I saw the array is empty .

doctor.js:

var express = require('express');
var router = express.Router();
var app=express()
var bodyParser = require("body-parser");
var validator = require('validator');
var mongo= require('./mongoconnect')
var authentication=require('./check_authentication')
var validate = require('./validation')
var ObjectId=require('mongodb').ObjectId

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

router.post('/',function(req,res)
{
    if(validate.name(req.body.name) && validate.length(req.body.name) && validate.empty(req.body.name))
    {
        if(validate.empty(req.body.hospital_id))
        {
            mongo.find("hospital","_id",ObjectId(req.body.hospital_id),function(result1)
            {
                if(result1.length==1)
                {
                    res.send("succcess")
                }
            })
        }
    }
})

module.exports = router;

And collection of MongoDB is:

hospital:

{ 
    "_id" : ObjectId("5aa92df0ec6b3cc78ff88afd"), 
    "name" : "apollo_hospitals"
}
{ 
    "_id" : ObjectId("5aa92df9ec6b3cc78ff88afe"), 
    "name" : "fortis"
}

mongoconnect.js:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var dbo=null;
exports.connection=function()
{
    if(dbo!=null) return 

  MongoClient.connect(url, function(err, db)
    {
       if (err) throw err;
       dbo = db.db("hospital_api");
    });
}
var get = function (){
    return dbo;
}
exports.find=function(collections,key,value,callback)
{
    get().collection(collections).find({key:value}).toArray(function(err,result)
    {
        // console.log(collections)
        // console.log(key)
        // console.log(value)
        if(err) throw err;
        console.log(result)
        callback(result)
    })
}

Here, myself i got the solution. We have to declare ObjectID with New keyword..

Var some_variable = New ObjectID(_id)

After that we can use that id anywhere using that some_variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM