Node.js 如何在mongoose模式中使用项的值

Node.js 如何在mongoose模式中使用项的值,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我想在模式中获取item的值,并在同一模式中使用它 例如有一个 const mongoose = require("mongoose"); const TestSchema = new mongoose.Schema({ appellant: String, respondent: String, title: `${this.appellant} V. ${this.respondent}`, }); module.exports = mongoose.model("

我想在模式中获取item的值,并在同一模式中使用它

例如有一个

const mongoose = require("mongoose");
const TestSchema = new mongoose.Schema({
    appellant: String,
    respondent: String,
    title: `${this.appellant} V. ${this.respondent}`,
});

module.exports = mongoose.model("Test", TestSchema);
通常,a用于这样的实例。它允许您使用特定格式的数据,而无需持久化数据和创建冗余数据

在您的情况下,它看起来是这样的:

TestSchema.virtual('title').get(function () {
   return this.appellant + ' V. ' + this.respondent
});
通常,a用于这样的实例。它允许您使用特定格式的数据,而无需持久化数据和创建冗余数据

在您的情况下,它看起来是这样的:

TestSchema.virtual('title').get(function () {
   return this.appellant + ' V. ' + this.respondent
});

正如我在回答中所说,Virtuals不会将值保存到数据库correct。您希望数据持久化两次有什么原因吗??一般来说,这是不好的做法。数据已经存储,您只需要以特定格式访问它。这就是为什么virtuals在这里是正确的解决方案,因为它避免了重复的数据存储。假设我使用virtuals,如何获取“title”的值?正如我在回答中所述,virtuals不会将值保存到数据库correct。您希望数据持久化两次有什么原因吗??一般来说,这是不好的做法。数据已经存储,您只需要以特定格式访问它。这就是为什么virtuals是正确的解决方案,因为它避免了重复的数据存储?