0
用戶有配置文件對象和一個配置的利益的NodeJS和快遞 - 嵌套路由器不打控制器功能
let UserSchema = new Schema({
email: {
value: {
type: String,
lowercase: true,
//unique: true,
},
token: String,
verified: Boolean,
},
password: {
type: String,
},
phone: {
countryCode: {
type: String,
//required:true,
unique: true,
},
number: {
type: String,
required: true
},
code: String,
verified: {
type: Boolean,
default: false
},
},
jwt: String,
profile: {
username: String,
firstname: String,
lastname: String,
dob: String,
level: Number,
location: String,
image: String,
introduction: String,
languages: {
teach: [{
code: String,
name: String,
native: String,
level: Number,
}],
learn: [{
code: String,
name: String,
native: String,
level: Number,
}],
},
interests: [],
countries: [],
},
},
{
timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}
});
我遇到的情況,我只是想利益添加到用戶配置文件的陣列。該請求會是這樣的,以顯示所有用戶的興趣。
GET:/用戶/:ID /資料/興趣
user.router.js
'use strict';
let express = require('express');
let router = express.Router();
let controller = require('../controllers/user.controller');
controller = new controller();
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.store);
router.put('/:id', controller.update);
router.delete('/:id', controller.destroy);
router.use('/:id/profile', require('./profile.route'));
module.exports = router;
profile.router.js
let express = require('express');
let router = express.Router({mergeParams: true});
let controller = require('../controllers/profile.controller');
controller = new controller();
router.get('/', controller.index);
router.get('/:id', controller.show);
router.post('/', controller.store);
router.put('/:id', controller.update);
router.delete('/:id', controller.destroy);
router.use('/interest', require('./interest.route'));
module.exports = router;
interest.router.js
'use strict';
let express = require('express');
let router = express.Router({mergeParams: true});
let controller = require('../controllers/interest.controller');
controller = new controller();
router.post('/', controller.store);
router.get('/', controller.show);
module.exports = router;
interest.controller.js
show(req, res) {
let id = req.params.id;
console.log(id);
User.findOne({'_id': id}, function (err, user) {
if (err) return res.json(err);
return res.json(user);
});
}
當我調用這個GET:/ users /:id/profile/interest請求時,它應該在感興趣的控制器中點擊show函數。但是,它並沒有這樣做。郵差給我一個錯誤。
{
"message": "Cast to ObjectId failed for value \"interest\" at path \"_id\" for model \"User\"",
"name": "CastError",
"stringValue": "\"interest\"",
"kind": "ObjectId",
"value": "interest",
"path": "_id"
}
我該如何解決這個問題?
P.S如果你能想到一個更有效的方法來做這個過程,請讓我知道。
是的,你是對的,如果我想在老地方我需要提供個人資料ID。所以我現在的問題是爲什麼我的配置文件對象沒有自己的ID? – Kay