gpt4 book ai didi

node.js - 如何在 Mongoose Schema 方法中指定 `this`

转载 作者:可可西里 更新时间:2023-11-01 10:43:08 25 4
gpt4 key购买 nike

我尝试在 Mongoose 中摆弄一下模式方法。我想知道如何从我正在使用的模式中调用信息,有点像使用 this

我的架构如下所示:

'use strict';

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

var BuildingSchema = new Schema({
name: String,
info: String,
level: { // The current level of the template, default value is 1
type: Number,
default: 1
},
ressource: { // Ressouces
level: [{
gain: [{ // Gain per level
amount: Number,
ressource: {
type: Schema.ObjectId,
ref: 'Ressource'
}
}],
cost: [{ // Cost per level
amount: Number,
ressource: {
type: Schema.ObjectId,
ref: 'Ressource'
}
}]
}]
},
storage: { // Storage
capacity: [{ // Storage capacity changes per level
inside: Number,
outside: Number
}],
stored: { // Stored
inside: [{ // Ressources stored inside
amount: Number,
ressource: {
type: Schema.ObjectId,
ref: 'Ressource'
}
}],
outside: [{ // Ressources stored outside
amount: Number,
ressource: {
type: Schema.ObjectId,
ref: 'Ressource'
}
}]
}
}
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true }
});

/**
* Methods
*/
BuildingSchema.methods = {
printThis: function() {
console.log('Print in prompt : ', this);
}
};

module.exports = mongoose.model('Building', BuildingSchema);

我从我的 Controller 调用这样的方法

console.log('Print in browser : ', building.printThis);

到目前为止,我的在提示中打印返回undefined

最佳答案

这里打印出了 printThis 方法:

> building = new Building()
{ _id: 554899217377c9b97c54bb36,
storage: { stored: { outside: [], inside: [] }, capacity: [] },
ressource: { level: [] },
level: 1,
id: '554899217377c9b97c54bb36' }
> building.printThis()
Print in prompt : { _id: 554899217377c9b97c54bb36,
storage: { stored: { outside: [], inside: [] }, capacity: [] },
ressource: { level: [] },
level: 1,
id: '554899217377c9b97c54bb36' }
undefined
>

关于node.js - 如何在 Mongoose Schema 方法中指定 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30049191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com