检查用户ID是否在猫鼬文档中-如果是,将属性值更改为true?

时间:2018-10-08 14:10:03

标签: node.js mongodb express mongoose

我有一个expressjs路由器,它使用mongoose findById方法查看MongoDB集合。它返回一个对象,该对象内部存在一个具有用户ID的userHasSelected数组。我不想返回用户ID,但只需检查数组中是否存在当前用户(发出请求的用户)。如果他是,则返回true而不是返回用户ID。

路由器中的verifytoken中间件向请求添加了一个用户ID属性。该用户ID在获取路由器消息中可用-我可以通过某种方式将其传递给Mongoose模式吗?

//我的路由器

router.get('/challenge/:challengeId', verifyToken ,function (req, res){
    //+ Return one challenge and its options
    //- Check if userId is set to options and winner properties
    let userId = req.userId;
    console.log(userId);
    let challengeId = req.params.challengeId;

    Challenge.findById(challengeId, (err, suc)=>{
        if(err){
            res.status(304).send(err);
        }
        Challenge.
        res.status(200).send(suc);
    });
})

//和猫鼬模式

const mongoose = require('mongoose');

var Schema = mongoose.Schema;

//Optionsschema is use in the ChallengeSchema
var OptionSchema = new Schema({
    name: { type: String},
    isCorrect : { type: Boolean },
    description: { type: String },
    image : { type : String },
    userHasSelected : { type : Object, get : returnUserChallengeStatus}
})

OptionSchema.set('toObject', { getters: true });
OptionSchema.set('toJSON', { getters: true });

var ChallengeSchema = new Schema({
    shortEventId : String,
    organization: String,
    name: String,
    winner: String,
    options : [OptionSchema]
});

ChallengeSchema.set('toObject', { getters: true });
ChallengeSchema.set('toJSON', { getters: true });

ChallengeSchema.virtual('born').get(function(value) {
    return this.name + "plus andet"
});

module.exports = mongoose.model('challenge', ChallengeSchema);

再说一次-我不想从userHasSelected数组返回用户ID-只检查他是否在那里,如果是,请使用getter或方法将value设置为true。

更新后的说明 findById返回此对象/文档

{
    "_id":"5b86dc5bfb6fc03893e55001",
    "shortEventId": "d2d3",
    "organization": "Braedstrup",
    "name": "1. december",
    "winner": "5b864cbaa9ce291b148ddd6d",
    "options": [
        {
            "name": "Matas",
            "isCorrect": "true",
            "description": "Matas er byens førende indenfor pleje og Matas er byens førende indenfor pleje og omsorg Matas er byens førende indenfor pleje og omsorg",
            "image": "https://cityxpstorage.blob.core.windows.net/images/Matas.png",
            "userHasSelected": [
                {
                    "userId": "5b864cbaa9ce291b148ddd6d"
                }
            ]
        },
        {
            "name": "Føtex",
            "isCorrect": "false",
            "description": "Føtex er en dejlig butik",
            "image": "https://cityxpstorage.blob.core.windows.net/images/Føtex.png"
        },
        {
            "name": "Kvickly",
            "isCorrect": "false",
            "description": "Kvickly er en dejlig butik",
            "image": "https://cityxpstorage.blob.core.windows.net/images/Matas.png"
        },
        {
            "name": "MC Jørgensen",
            "isCorrect": "false",
            "description": "MC Jørgensen er en dejlig butik",
            "image": "https://cityxpstorage.blob.core.windows.net/images/Matas.png"
        }
    ],
    "startDate": "2018-10-06T00:00:00.000Z",
    "endDate": "2018-10-06T23:59:00.000Z"
}

因此,嵌套数组'userHasSelected'包含有关用户ID的信息。我不想发送该邮件,而是希望发送一个{userId:true}。 我读过,吸气剂能够处理传出数据。

可能的解决方案

像这样将对象返回给客户端之前,我可以在路由器的get方法中进行检查

// If user is in array set user to true. I would like to move this responsibility to the schema / document.
suc.options.forEach(option => {
    if(Array.isArray(option.userHasSelected))
    option.userHasSelected = {userId : true}
});

但是我真的希望模式对此负责-可能吗?

1 个答案:

答案 0 :(得分:0)

我遇到了类似的问题并找到了解决方法。只需在您负责的模态模式上创建一个可选字段,我们称之为“状态”。在您的控制器上,检查您的数组是否包含请求的用户 ID 并写入该字段。例如;

在你的架构上;

    caseStatus: {
        type: Boolean,
        required: false
    },  
    voters: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
    }],

然后在您的控制器上;

    let theCase = await Case.find({speciality: res.locals.user_speciality }).exec();

            let status = theCase.voters.includes(res.locals.user_id);
            caseItem.caseStatus = status;