在 Keystone 'save' 之后添加一个新的 属性 到 mongo
Adding a new property to mongo after 'save' in Keystone
我最近发现如何在使用 Keystone JS () 时更改现有 属性 的值并将其保存到 mongo 数据库。
现在我需要添加一个新的 属性 并在同一 pre('save')
阶段将其保存到数据库中。
目的是说,如果游戏的结果(现有属性)是'Won',那么添加一个新的属性 'won',这是一个布尔值(真的)。如果重要的话,我想要这个的原因是因为在车把模板中我想说 {{#if won}}class="success"{{/if}}
Game.schema.pre('save', function(next) {
if (this.isModified('result')) {
if (this.result === 'Won') {
this.won = true;
}
}
next()
});
但是没有任何反应。我读到您不能添加属性,除非它们已在模式中设置。所以我尝试在上面添加 Game.schema.set('won', false);
,但仍然没有。
有没有简单的方法可以做到这一点?
您可以查看 Mongoose virtuals,这是您可以获取和设置但不会持久保存到数据库的属性:
Game.schema.virtual('won').get(function() {
return this.result === 'Won'
})
http://mongoosejs.com/docs/guide.html#virtuals
如果您只想在您的模板中使用它,那么您还可以在您的视图中的 locals 上设置一个特定的 属性。
也许是这样的:
...
exports = module.exports = function(req, res) {
var view = new keystone.View(req, res)
var locals = res.locals
locals.games = []
view.on('init', function(next) {
var query = {} // Add query here
Game.model.find(query).exec(function(err, games) {
// Handle error
games.forEach(function(game) {
game.won = game.result === 'Won'
})
locals.games = games
})
})
}
...
我最近发现如何在使用 Keystone JS (
现在我需要添加一个新的 属性 并在同一 pre('save')
阶段将其保存到数据库中。
目的是说,如果游戏的结果(现有属性)是'Won',那么添加一个新的属性 'won',这是一个布尔值(真的)。如果重要的话,我想要这个的原因是因为在车把模板中我想说 {{#if won}}class="success"{{/if}}
Game.schema.pre('save', function(next) {
if (this.isModified('result')) {
if (this.result === 'Won') {
this.won = true;
}
}
next()
});
但是没有任何反应。我读到您不能添加属性,除非它们已在模式中设置。所以我尝试在上面添加 Game.schema.set('won', false);
,但仍然没有。
有没有简单的方法可以做到这一点?
您可以查看 Mongoose virtuals,这是您可以获取和设置但不会持久保存到数据库的属性:
Game.schema.virtual('won').get(function() {
return this.result === 'Won'
})
http://mongoosejs.com/docs/guide.html#virtuals
如果您只想在您的模板中使用它,那么您还可以在您的视图中的 locals 上设置一个特定的 属性。
也许是这样的:
...
exports = module.exports = function(req, res) {
var view = new keystone.View(req, res)
var locals = res.locals
locals.games = []
view.on('init', function(next) {
var query = {} // Add query here
Game.model.find(query).exec(function(err, games) {
// Handle error
games.forEach(function(game) {
game.won = game.result === 'Won'
})
locals.games = games
})
})
}
...