如何向req.body添加元素?

时间:2019-02-06 05:13:11

标签: javascript node.js mongodb request body-parser

我正在尝试使用MongoDB集合并将一个集合与另一个集合相关联。我有一个名为“ player”的收藏集,一个名为“ calendar”的收藏集,我试图将日历信息添加到日历事件中,以便只有登录系统的玩家才能看到其特定事件。

当我控制台日志req.body时,我可以看到该事件的所有信息:

{ start_date: '2019-02-09 00:00',
end_date: '2019-02-09 00:05',
text: 'New event',
id: '5c5a6bc5ea427e54cd4714d6',
'!nativeeditor_status': 'updated' }

您看到的ID是事件ID。我想使用护照(req.user.id)添加字段userID,这样我就可以搜索集合并填充已登录播放器的事件。

我的问题是如何向req.body元素添加字段?我的日历和播放器架构如下:

player.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    },
    calendar: {
        type: Schema.Types.ObjectId, ref: 'calendar'
    }
});

const User = mongoose.model('player', UserSchema);

module.exports = User;

calendar.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({
    text: {type: String, required: true},
    start_date: {type: Date, required: true},
    end_date:   {type: Date, required: true},
    user: {type: Schema.Types.ObjectId, ref: 'player', required: true}
});

const calendar = mongoose.model('calendar', schema);

module.exports = calendar;

这是我在路线index.js中实现日历的方式:

    //schedule
    router.get('/calendar', ensureAuthenticated, function(req, res){
        req.body.user = req.user.id;
        var db = require('mongoskin').db("mongodb://tdipietro87:tdipietro87@tmcluster-shard-00-00-pbtwu.mongodb.net:27017,tmcluster-shard-00-01-pbtwu.mongodb.net:27017,tmcluster-shard-00-02-pbtwu.mongodb.net:27017/test?ssl=true&replicaSet=TMCluster-shard-0&authSource=admin&retryWrites=true", { w: 0});
        db.bind('calendar');

        var Calendar = require('../models/calendar');

        Calendar.find({user: req.user.id}) // query by specific user
    .then(function (data) {
        // ...


            router.use(express.static(path.join(__dirname, 'public')));
            router.use(bodyParser.json());
            router.use(bodyParser.urlencoded({ extended: true }));

            router.get('/init', function(req, res){
                db.calendar.insert({ 
                    text:"My test event A", 
                    start_date: new Date(2018,8,1),
                    end_date:   new Date(2018,8,5)
                });
                db.calendar.insert({ 
                    text:"My test event B", 
                    start_date: new Date(2018,8,19),
                    end_date:   new Date(2018,8,24)
                });
                db.calendar.insert({ 
                    text:"Morning event", 
                    start_date: new Date(2018,8,4,4,0),
                    end_date:   new Date(2018,8,4,14,0)
                });
                db.calendar.insert({ 
                    text:"One more test event", 
                    start_date: new Date(2018,8,3),
                    end_date:   new Date(2018,8,8),
                    color: "#DD8616"
                });

                res.send("Test events were added to the database")
            });


            router.get('/data', function(req, res){
                db.calendar.find().toArray(function(err, data){
                    //set id property for all records
                    console.log(err);
                    for (var i = 0; i < data.length; i++)
                        data[i].id = data[i]._id;

                    //output response
                    res.send(data);
                });
            });


            router.post('/data', function(req, res){
                console.log(req.body);
                console.log(req.user.id);
                var data = req.body;
                var mode = data["!nativeeditor_status"];
                var sid = data.id;
                var tid = sid;

                delete data.id;
                delete data.gr_id;
                delete data["!nativeeditor_status"];


                function update_response(err, result){
                    if (err)
                        mode = "error";
                    else if (mode == "inserted")
                        tid = data._id;

                    res.setHeader("Content-Type","application/json");
                    res.send({action: mode, sid: sid, tid: tid});
                }

                if (mode == "updated")
                    db.calendar.updateById( sid, data, update_response);
                else if (mode == "inserted")
                    db.calendar.insert(data, update_response);
                else if (mode == "deleted")
                    db.calendar.removeById( sid, update_response);
                else
                    res.send("Not supported operation");
            });


        res.render('calendar', {
            name: req.user.name
        })
    });
    });

1 个答案:

答案 0 :(得分:0)

这很复杂,但是我想提供一些线索

const newEvent = new Calendar({ //Calendar is your models name
      ....fill with another required field in models
      text : req.body.text,
      user : req.user.id //look again, how you decode incoming token request and declare them
});