使用mongoose按ObjectID查找始终返回null

时间:2017-10-26 04:46:50

标签: mongodb express mongoose

我想搜索具有ObjectId类型的_id属性的文档。但即使存在具有完全_id的文档,它也会一直返回null。

const employee = require("../Models/employee");

router.get('/employees/:id', function(req,res){
    console.log(req.params.id);
    employee.findById(req.params.id).exec(function(err, emp){
        if(err) {
            res.send("Error! " + err);
        } else {
            res.json(emp);
        }
    })
});

员工模特:

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const empSchema = new Schema({
    _id: String,
    Name: String,
    DOB: String,
    Sex: String,
    Experience: Number,
    Expertise: String,
});

module.exports = mongoose.model('employee', empSchema, 'EmpDetails');

MongoDB有_id:

{ 
    "_id" : ObjectId("59eebab187179c880ed9473b"), 
    "Name" : "Abhisek", 
    "DOB" : "04/28/1991", 
    "Sex" : "Male", 
    "Experience" : 4.0, 
    "Expertise" : "Javascript"
}

控制台也会显示相同的

59eebab187179c880ed9473b

0 个答案:

没有答案