POST数据不保存数组 [英] POST data does not save arrays

查看:44
本文介绍了POST数据不保存数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Mongo和Express的新手.我正在构建一个简单的应用程序,公司在该应用程序中向员工发送问题以请求反馈.我正在努力将员工(用户)作为问题放入问题文档中.这是我的模式[不确定我是否正确编写了它们].

I am new to Mongo and Express. I'm building a simple app where a company sends out a question to its employees requesting for feedback. I'm struggling to put employees(users) in the question document as an array. Here are my Schemas [Not sure if I've written them correctly].

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

更新(员工表)

推荐答案

这是因为您实际上并未将用户引用数组传递给 employees 字段.

It's because you're not actually passing an array of user references to employees field.

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

您打算怎么做是另一回事.如果用户可用,您可以在发布请求中传递数组,在这种情况下,它将在 req.body.employees 中可用,或者传递用户ID和您刚刚创建的问题彼此.

How you plan to do that is another matter. You can either pass the array in post request if users are available, in which case it'll be available in req.body.employees, or pass the ids of the user and question you're just creating to each other.

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;
    });
});

这篇关于POST数据不保存数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆