Express:mongodb猫鼬链接实体 [英] Express: mongodb mongoose linking entities

查看:46
本文介绍了Express:mongodb猫鼬链接实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个简单的Web应用程序,公司在该应用程序中向员工发送问题以请求反馈.仍在学习mongodb.整周都在玩它在论坛上提供了一些有用的帮助后,我逐渐了解了它,但是直到现在,我才意识到我一直在使用有缺陷的思维过程来设计架构.我最初使用的是用户的 response 作为 UserSchema 中的字段,但是由于我意识到这不是用户的财产而是我将其删除(如此处注释),一个不断变化的变量(是/否/空).我现在必须创建一个单独的 AnswersSchema (有人告诉我我需要一个,但我固执地反对它-在启动该项目时觉得没有意义),现在我已经完成了(正确如果写错/想错了,则为我).我现在的问题是如何修改api中的查询,以在 router post 中的 save 操作上将所有三个实体链接在一起?请注意此处显示的 save 操作代码有效,但存在缺陷,因为当用户将响应作为其属性之一时.因此,在删除 UserSchema 上的响应后,现在只有用户名显示在有角前端上.

I'm building a simple web app where a company sends out a question to its employees requesting for feedback. Still learning about mongodb. Been playing around with it all week & I'm slowly getting a good hang of it with some helpful assistance on the forums but only now I realize I have been using a flawed thought process to design the schema. I was initially using a user's response as a field in the UserSchema but I have now removed it (as commented out here) as I realized this is not a user's property but rather a variable that keeps changing (yes/no/null). I now have to create a separate AnswersSchema (I was told I'll need one but I stubbornly argued against it - saw no sense in at the time I started the project) which I have done now (correct me if it's wrongly written/thought out). My question now is how do I modify my query in the api to link all the three entities together on a save operation in the router post? Please note the save operation code shown here works but is flawed as it's for when the user has a response as one of their properties. So now only the user's name shows up on the angular front-end after I removed response on UserSchema which makes sense.

var QuestionSchema = Schema({
    id          : ObjectId,
    title       : String,
    employees   : [{ type: ObjectId, ref: 'User'}]
});

var UserSchema = Schema({
    username    : String,
    //response    : String,
    questions   : [{ type: ObjectId, ref: 'Question'}]
});  

//new schema/collection I've had to create
var AnswerSchema = Schema({
    response    : {type :String, default:null},
    question    : { type: ObjectId, ref: 'Question'},
    employees   : [{ type: ObjectId, ref: 'User'}],
})

module.exports = mongoose.model('Question', QuestionSchema);
module.exports = mongoose.model('User', UserSchema);
module.exports = mongoose.model('Answer', AnswersSchema);

api.js

Question.findOne({ title: 'Should we buy a coffee machine?'}).exec(function(err, question) {
          //example data
          var user = new User([{
            "username": "lindelof",
            "response": "yes",
          },{
            "username": "bailly",
            "response": "no",
          },{
            "username": "suzan",
            "response": "yes",
          }]);

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

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

        });
        console.log('entry saved >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>');
    }

更新

推荐答案

通过添加 AnswerSchema ,您做对了事,因为这是多对多关系.一个问题可以由许多用户(员工)回答.用户可以回答许多问题.因此,最好将答案作为两者之间的关联集合.

You did the right thing by adding AnswerSchema, as it's a many to many relationship. A question can be answered by many users (employees). A user can answer many questions. Therefore, it's good to have answer as an associative collection between the two.

考虑到这种关系,您需要稍微更改一下架构:

With this relationship in mind, you need to change your schema a little:

var QuestionSchema = Schema({
    id          : ObjectId,
    title       : String,
    //employees   : [{ type: ObjectId, ref: 'User'}]
});

var UserSchema = Schema({
    username    : String,
    //response    : String,
    //questions   : [{ type: ObjectId, ref: 'Question'}]
});  

var AnswerSchema = Schema({
    response    : {type :String, default:null},
    question    : { type: ObjectId, ref: 'Question'},
    employee   : { type: ObjectId, ref: 'User'},  //a single employee
});

现在,要知道某个用户是否已经回答了问题,只需用其ID和问题的ID搜索 Answer :

Now, to know if a certain user has answered a question already, just search Answer with his and the question's ids:

Answer.findOne({
        question: questionId,
        employee: userId
    })
    .exec(function(err, answer) {
        if (err) {

        } else if (!answer) {
            //the employee has not answered this question yet
        } else {
            //answered
        }
    });

最后,您的submit-answer API应该包含一个包含questionId和userId的正文(如果已登录,您还可以从会话或令牌中获取userId).此路由更新现有答案,否则创建它(仅用于创建 create 函数)

Lastly, your submit-answer API should expect a body that contains questionId and userId (if signed in, you can get userId from session or token also). This route updates existing answer, else creates it (for create-only use create function)

router.post('/', function(req, res) {
            //req.body = {question: "594315b47ab6ecc30d5184f7", employee: "594315d82ee110d10d407f93", response: "yes"}
            Answer.findOneAndUpdate({
                    question: req.body.question,
                    employee: req.body.user
                },
                req.body, 
                {
                    upsert: true  //updates if present, else inserts
                }
            })
        .exec(function(err, answer) {
            //...
        });
});

这篇关于Express:mongodb猫鼬链接实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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