【发布时间】:2017-11-17 05:15:19
【问题描述】:
我是 Mongo 和 Express 的新手。我正在构建一个简单的应用程序,公司向其员工发送问题以征求反馈意见。我正在努力将员工(用户)作为数组放入问题文档中。这是我的模式[不确定我是否写对了]。
//question schema
var QuestionSchema = Schema({
id : ObjectId,
title : String,
employees : [{ type: ObjectId, ref: 'User'}]
});
module.exports = mongoose.model('Question', QuestionSchema);
//user schema
var UserSchema = Schema({
username : String,
response : String,
questions : [{ type: ObjectId, ref: 'Question'}]
});
module.exports = mongoose.model('User', UserSchema);
api.js
router.post('/', function (req, res) {
// make sure user is authenticated
User.findOne({ username: req.body.username }).exec(function(err, user) {
if(err) throw err;
if(!user) {
res.json({ success: false, message: 'Could not authenticate user' })
} else if (user){
/*----------------save example----------------------*/
var question = new Question({ title: 'Should we buy a coffee machine?'});
question.save(function (err) {
if (err) throw err;
var user1 = new User({
username: "marcopolo",
response: "yes",
});
user1.save(function (err) {
if (err) throw err;
});
});
console.log('entry saved >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
}
});
});
UPDATE(员工表)
【问题讨论】:
-
您确定 QuestionSchema 中自动实现的 id 有效吗?我指的是“ObjectId”
-
@Jesper 是的。我添加了第二个快照以显示其员工表存在相同问题。不显示问题数组中回答的问题