我收到TypeError:尝试根据用户ID获取用户时,无法读取未定义的属性'_id'。
我的路线和控制器看起来像这样:
// routes.js
var AuthenticationController = require('./controllers/authentication');
module.exports = function (app){
var apiRoutes = express.Router();
apiRoutes.get('/user/:_id', AuthenticationController.getUserById);
app.use('/api', apiRoutes);
};
//控制器
exports.getUserById = function (req, res, next){
User.findById(
{_id: req.params._id}, function(err,users){
if (err){
res.send(err);
}
res.status(200).json({
Success: true,
user: users
});
});
};
下面是我用于按ID获取用户的单元测试代码。
// user-test.spec.js
describe('/GET/:_id user', () => {
it('it should get a user by the given ID', (done) => {
var user = new User({ email: "mjn.nilesh12@gmail.com", password: "gunners", fullname: "Nilesh Maharjan"});
user.save((err, user) => {
chai.request(server)
.get('api/user/' + user._id)
.send(user)
.end((err, res) => {
res.should.have.status(200);
done();
});
});
});
});
//完全错误
Uncaught TypeError: Cannot read property '_id' of undefined
at user.save (test/user-test.spec.js:73:38)
at /Users/seva/Desktop/project1/node_modules/mongoose/lib/model.js:4670:16
at /Users/seva/Desktop/project1/node_modules/mongoose/lib/utils.js:250:11
at $__save.error (node_modules/mongoose/lib/model.js:476:16)
at /Users/seva/Desktop/project1/node_modules/kareem/index.js:246:48
at next (node_modules/kareem/index.js:167:27)
at next (node_modules/kareem/index.js:169:9)
at Kareem.execPost (node_modules/kareem/index.js:217:3)
at _handleWrapError (node_modules/kareem/index.js:245:21)
at _cb (node_modules/kareem/index.js:304:16)
at /Users/seva/Desktop/project1/node_modules/mongoose/lib/model.js:329:9
at /Users/seva/Desktop/project1/node_modules/kareem/index.js:135:16
at _combinedTickCallback (internal/process/next_tick.js:132:7)
at process._tickCallback (internal/process/next_tick.js:181:9)