POST数据不保存数组

时间:2017-06-14 21:38:47

标签: node.js express mongoose

我是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 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
        }
    });
});

enter image description here

更新(员工表)

enter image description here

1 个答案:

答案 0 :(得分:2)

这是因为你实际上没有将一组用户引用传递给employees字段。

var question = new Question({ title: 'Should we buy a coffee machine?', employees: [array of user references]});

你打算如何做到这一点是另一回事。如果用户可用,您可以在帖子请求中传递数组,在这种情况下,它可以在req.body.employees中使用,或传递用户的ID并且您只是相互创建的问题。

var question = new Question({
    title: 'Should we buy a coffee machine?'
});
var user1 = new User({
    username: "marcopolo",
    response: "yes",
});

question.employees = [user1._id];
user1.questions = [question._id];

question.save(function(err) {
    if (err) throw err;
    user1.save(function(err) {
        if (err) throw err;
    });
});