2015-06-09 3 views
1

Данная схема yon, как я могу сэкономить userId до createdBy и updatedBy?Как сохранить userId в мангусте?

Кажется, что это должен быть простой вариант использования. Как мне это сделать?

Я не уверен, как получить userId от req.user.id до модели, прежде чем писать.

// graph.model.js 

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

var schema = new Schema({ 
    title: String, 

    createdAt: Date, 
    createdBy: String, 
    updatedAt: Date, 
    updatedBy: String, 
}); 

// This could be anything 
schema.pre('save', function (next) { 
- if (!this.createdAt) { 
    this.createdAt = this.updatedAt = new Date; 
    this.createdBy = this.updatedBy = userId; 
    } else if (this.isModified()) { 
    this.updatedAt = new Date; 
    this.updatedBy = userId; 
    } 
    next(); 
}); 

Вот код контроллера, если вы заинтересованы:

var Graph = require('./graph.model'); 

// Creates a new Graph in the DB. 
exports.create = function(req, res) { 
    Graph.create(req.body, function(err, thing) { 
    if(err) { return handleError(res, err); } 
    return res.status(201).json(thing); 
    }); 
}; 

// Updates an existing thing in the DB. 
exports.update = function(req, res) { 
    if(req.body._id) { delete req.body._id; } 
    Graph.findById(req.params.id, function (err, thing) { 
    if (err) { return handleError(res, err); } 
    if(!thing) { return res.send(404); } 
    var updated = _.merge(thing, req.body); 
    updated.save(function (err) { 
     if (err) { return handleError(res, err); } 
     return res.json(thing); 
    }); 
    }); 
}; 

ответ

2

Вы не можете получить доступ к req объект внутри мангустов крючка.

Я думаю, вы должны определить виртуальное поле с помощью смарт-сеттера вместо:

schema.virtual('modifiedBy').set(function (userId) { 
    if (this.isNew()) { 
    this.createdAt = this.updatedAt = new Date; 
    this.createdBy = this.updatedBy = userId; 
    } else { 
    this.updatedAt = new Date; 
    this.updatedBy = userId; 
    } 
}); 

Теперь все, что вам нужно сделать, это установить modifiedBy поле с правильным userId значением в контроллере:

var updated = _.merge(thing, req.body, { 
    modifiedBy: req.user.id 
}); 
Смежные вопросы