我最近一直在学习 MongoDB 和 Mongoose,以努力学习 MEAN 堆栈。使用本课程:https ://www.edx.org/course/introduction-mongodb-using-mean-stack-mongodbx-m101x我正在尝试为我的产品架构创建一个虚拟的,以更加用户友好的方式显示价格方法。但是,当打印出这个虚拟时displayPrice
,它会显示为未定义,除非通过访问,否则toObject
USDtoJSON
符号会显示为问号。对于任何愚蠢和明显的疏忽,我深表歉意,我是这个数据库的新手,找不到很多简单解释事情的教程。
这是代码:
var mongoose = require("mongoose");
var Category = require("./categoryschema.js");
var productSchema = {
name: {
type: String,
required: true
},
// Pictures must start with http://"
pictures: [{ type: String, match: /^http:\/\//i }],
price: {
amount: {
type: Number,
required: true
},
currency: {
type: String,
enum: ["USD", "EUR", "GBP"],
required: true
}
},
category: Category.categorySchema
};
module.exports = new mongoose.Schema(productSchema);
module.exports.productSchema = productSchema;
var schema = new mongoose.Schema(productSchema);
var Product = mongoose.model("Product", schema);
var currencySymbols = {
"USD": "$",
"EUR": "E",
"GBP": "P"
};
// Make human readable string form of price. "$25" instead of "25 USD"
schema.virtual("displayPrice").get(function() {
return currencySymbols[this.price.currency] + "" + this.price.amount;
});
schema.set("toObject", { virtuals: true });
schema.set("toJSON", { virtuals: true });
var p = new Product({
name: "test product",
price: {
amount: "33.58",
currency: "USD"
}
});
console.log(p.displayPrice);
p.price.amount = 20;
console.log(p.displayPrice);
p.price.currency = "EUR";
console.log(JSON.stringify(p));
var obj = p.toObject();
console.log(obj.displayPrice);
输出:
undefined
undefined
{"name":"test product","_id":"569c39774093336c149eba2c","category":{"ancestors":
[]},"price":{"amount":20,"currency":"EUR"},"pictures":[],"displayPrice":"E20","i
d":"569c39774093336c149eba2c"}
E20