我可以在mongoose.js模型中填充ref而不是每次查询吗?

时间:2016-01-24 23:26:57

标签: node.js mongodb mongoose

简介:我正在使用Node和Mongo创建一个StackExchange克隆来学习该语言。我目前正在研究API。

我有以下' questionSchema':

var questionSchema = new Schema({
  _id       : {type: String, default: shortid.generate},
  title     : {type: String, required: true},
  question  : {type: String, required: true},
  user      : {type: Schema.ObjectId, ref: 'User'},
  points    : {type: Number, default: 0},
  date      : {type: Date, default: Date.now},
  answers   : [answerSchema],
  votes     : [{
                  user: {type: Schema.ObjectId, ref: 'User', required: true},
                  vote: {type: Number, enum: [-1,0,1]}
              }],
  __v       : {type: Number, select: false}
});

这个想法是,当用户对某个问题进行投票时,点数字段会递增(或递减),并且用户ID和投票会添加到投票数组中。我有投票数组来检测用户是否已经投票并阻止额外投票。

问题:我实际上无法检查用户是否已投票(检查他们的用户ID是否存在于投票数组中)。我一直在玩添加方法'hasVoted'问题解决方案但是:

  1. 我不确定如何实际进行检查。
  2. 我也不确定在查询期间(在MongoDB中)是否有办法过滤投票数组,而不是在节点获得结果之后。
  3. 这是我尝试的方法,我知道这是错误的:

    //Has the user already voted on this question?
    questionSchema.methods.hasVoted = function (userid, cb) {
      this.votes.filter(function(vote) {
        if(userid == vote._id) {
            return '1';
        } else {
            return '0';
        }
      });
    };
    

1 个答案:

答案 0 :(得分:2)

我建议像这样制作投票架构

var voteSchema = new Schema({
  user: {type: Schema.ObjectId, ref: 'User', required: true},
  vote     : {type: Number, required: true}
})
var questionSchema = new Schema({
  _id       : {type: String, default: shortid.generate},
  title     : {type: String, required: true},
  question  : {type: String, required: true},
  points    : {type: Number, default: 0},
  date      : {type: Date, default: Date.now},
  answers   : [answerSchema],
  votes     : [{type: Schema.ObjectId, ref: 'Vote', required: false}]
});

然后得到你的问题并通过所有投票。

QuestionSchema.findById(question.id)
     .populate('votes')
     .exec(function (err, question) {
     // go through all the votes here
 }

或查询投票中是否存在您的用户ID问题

 QuestionSchema.find()
     .and([{_id:questionId,},{votes.user:userId}])
     .populate('votes') //dunno if you really have to populate i think you don't have to
     .exec(function (err, user) {
     // check if(user)
 }

或者像这里描述的那样findOne Subdocument in Mongoose

// EDIT 或者如果你不改变你的架构

QuestionSchema.find({votes.user:userId})
 .exec(function (err, user) {
   // should return ALL questions where the user id is in the votes your want a specific question do it in a and like in the example above
 }

如果您只想要数组中的一个元素,则必须进行如此处所述的投影How to find document and single subdocument matching given criterias in MongoDB collection