简体   繁体   中英

Mongoose: Creating a 'virtual column' of values

This is somewhat vague question, but please, bear with me:)

example schema:

var scoreSchema = mongoose.Schema ({
    name : String,
    scores : String
});

Example row: name: John, scores: "2, 4, 6, 1, 7"

for every row, i need to convert the scores string into array and sort. scores.split(",").sort(); Only this resulting array will ever be used, but i'd still need to keep the original long string in the database.

So I need to create some sort of 'virtual' column or reference which can be easily accessed later. Is there any way to accomplish this?

You can use Mongoose's virtuals support for this:

scoreSchema.virtual('splitScores').get(function() {
    return this.scores.split(",").sort();
});

With that in place, any score document instance will have a splitScores property that's the sorted array version of scores .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM