我可以填充ref的mongoose.js模型而不是每次我查询?
简介 :我正在使用Node和Mongo创build一个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} });
这个想法是,当用户对问题进行投票时,点字段会递增(或递减),并将用户标识和投票添加到投票数组中。 我有投票数组来检测用户是否已经投票,并防止额外的投票。
问题 :我有麻烦实际检查用户是否投票(检查他们的用户标识是否存在于投票数组中)。 我一直玩弄添加方法hasVoted到questionSchema,但是:
- 我不确定如何真正使支票发生。
- 我也不确定是否有一种方法可以在查询过程中(在MongoDB上)过滤votes数组,而不是在节点获取结果之后。
这是我的方法,我知道是错误的尝试:
//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'; } }); };
我会build议像这样做投票模式
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 }
或者在投票中查询您的用户标识是否有问题
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) }
或者像这里描述的那样在Mongoose中find一个子文档
/ /编辑或如果你不改变你的架构
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 }
如果你只想从数组中的一个元素,你必须进行像这里描述的投影如何find文档和单个子文档在MongoDB集合中给定的准则匹配