2017-03-22 80 views
1

我目前正在用MongoDB/Mongoose建立一個Node後端,我似乎有一些問題將我的數據綁在一起。具體而言,我希望所有用戶都能夠提交表單(問題表單),然後將其添加到「問題」集合中。除了被添加到問題集合之外,我還需要存儲用戶直接在用戶對象內部回答的所有問題的引用。CastError:拋出ObjectId失敗的價值......在路徑「問題」

下面你可以查看我的代碼。每當我對/questions發出POST請求時,它都會吐出這個錯誤。我應該注意到它成功地將文檔添加到問題集合中,並且每個問題都包含創建它的用戶的ID,但主要問題是用戶的questions陣列沒有得到更新以包括提交的問題的ID值。

型號/ user.js的

const mongoose = require('mongoose'), 
     Schema = mongoose.Schema, 
     bcrypt = require('bcrypt-nodejs'); 


const UserSchema = new Schema({ 
    email: { 
    type: String, 
    lowercase: true, 
    unique: true, 
    required: true 
    }, 
    password: { 
    type: String, 
    required: true 
    }, 
    profile: { 
    firstName: { type: String }, 
    lastName: { type: String } 
    }, 
    questions: [ 
    { 
     type: Schema.Types.ObjectId, 
     ref: 'Question' 
    } 
], 
    role: { 
    type: String, 
    enum: ['Member', 'Client', 'Owner', 'Admin'], 
    default: 'Member' 
    }, 
    resetPasswordToken: { type: String }, 
    resetPasswordExpires: { type: Date } 
}, 
{ 
    timestamps: true 
}); 

/** Pre-save of user to database, 
    hash password if password is modified or new 
*/ 
module.exports = mongoose.model('User', UserSchema); 

型號/ Question.js

const mongoose = require('mongoose'), 
     Schema = mongoose.Schema; 

// Schema defines how questions will be stored in MongoDB 
const QuestionSchema = new Schema({ 
    questionString: String, 
    answer: Boolean, 
    _createdBy : [ 
    { 
     type: mongoose.Schema.Types.ObjectId, 
     ref: 'User' 
    } 
], 
},{ 
    //user timestamps to save date created as .createdAt 
    timestamps: true 
}); 


module.exports = mongoose.model('Question', QuestionSchema); 

控制器/ QuestionController.js

const jwt = require('jsonwebtoken'), 
     crypto = require('crypto'), 
     Question = require('../models/question'), 
      User = require('../models/user'), 
     config = require('../config/main'); 


function setQuestionInfo(request) { 
    return { 
    _id: request._id, 
    questionString: request.questionString, 
    answer: request.answer, 
    user: request.user 
    } 
} 

exports.addQuestion = function(req, res, next) { 

User.findById(req.user.id, (err, user) => { 
if (err) throw new Error(err); 

// We create an object containing the data from our post request 
    const newQuestion = { 
    questionString: req.body.questionString, 
    answer: req.body.answer, 
    // in the author field we add our current user id as a reference 
    _createdBy: req.user._id 
    }; 

    // we create our new post in our database 
    Question.create(newQuestion, (err, question) => { 
     if (err) { 
     res.redirect('/'); 
     throw new Error(err); 
     } 

     // we insert our newQuestion in our posts field corresponding to the user we found in our database call 
     user.questions.push(newQuestion); 
     // we save our user with our new data (our new post). 
     user.save((err) => { 
     return res.send('sucess!'); 
     }); 
    }) 
    }); 
} 

Router.js

module.exports = function(app) { 
    // Initializing route groups 
    const apiRoutes = express.Router(), 
     userRoutes = express.Router(), 
     authRoutes = express.Router(), 
     questionRoutes = express.Router(); 

    //========================= 
    // Auth Routes 
    //========================= 

    /** ROUTES BELOW WORK FINE -- ONLY DEALS WITH POST TO /questions 
    * 


    app.use middle ware sets /auth as auth route (everything goes through /api/auth) 
    apiRoutes.use('/auth', authRoutes); 
    apiRoutes.get('/dashboard', requireAuth, function(req, res) { 
    res.send('It worked! User id is: ' + req.user._id + '.'); 
    }); 


    // Set user routes as a subgroup/middleware to apiRoutes 
    apiRoutes.use('/user', userRoutes); 

    // View user profile route 
    userRoutes.get('/:userId', requireAuth, UserController.viewProfile); 

    // Test protected route 
    apiRoutes.get('/protected', requireAuth, (req, res) => { 
    res.send({ content: 'The protected test route is functional!' }); 
    }); 
    // Registration route 
    authRoutes.post('/register', AuthenticationController.register); 
    // Login route 
    authRoutes.post('/login', requireLogin, AuthenticationController.login); 
    */ 

    // Problem Area --> Making POST req to /questions 
    apiRoutes.post('/questions', requireAuth, QuestionController.addQuestion); 

    // Set url for API group routes 
    app.use('/api', apiRoutes); 
}; 
+0

Hi Thomas Greco;這是你粘貼在那裏的一段代碼。你可以嘗試將它修改爲[最小,完整和可驗證示例](https://stackoverflow.com/help/mcve)? –

+1

我的歉意我沒有意識到我必須在模型中爲每個集合添加兩次,但是我經歷了並刪除了與我的問題無關的一小段代碼。我只包括AuthController和其他auth相關的東西,以顯示API工作正常(除了這個實例:P) –

+1

你可以嘗試'user.questions.push(question._id);'而不是'user.questions .push(newQuestion);'? – Veeram

回答

1

您已在架構定義爲接受的問題ID的用戶。

questions: [ 
    { 
     type: Schema.Types.ObjectId, 
     ref: 'Question' 
    } 

在保存與Question.create(newQuestion, (err, question)...回調屬性question有更新的數據,一個與ObjectId

現在您將此ObjectId值添加到您從findByIdUser型號獲得的現有questions陣列。

user.questions.push(question._id); 

貓鼬將使用questionId當你的問題陣列使用populate來填補你的問題的對象,但是對於檢索信息那一部分。

+0

太棒了。非常感謝! –

相關問題