【问题标题】:POST data does not save arraysPOST 数据不保存数组
【发布时间】: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 是的。我添加了第二个快照以显示其员工表存在相同问题。不显示问题数组中回答的问题

标签: node.js express mongoose


【解决方案1】:

这是因为您实际上并未将用户引用数组传递给 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;
    });
});

【讨论】:

  • 成功了!谢谢。现在我至少可以在questionsemployees 数组中看到一名员工。即使我创建了一个数组,我现在也在努力增加更多的员工。我可能会发布另一个问题并在链接中引用这个问题。
猜你喜欢
  • 2018-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-24
  • 2013-10-12
  • 2021-10-04
  • 1970-01-01
  • 2012-07-25
相关资源
最近更新 更多