如何在猫鼬中查找文档时剪切文本?

How to cut text on finding documents in mongoose?

我有以下架构:

var PostModel = mongoose.model('PostModel', {
    text : {type : String, default: ''},
    created_at : Date
});

text 字段可能很长(大约 1000 个字符)。当我在我的帖子列表页面上查询帖子时,我需要查询 All posts with cut text field to 150 characters only.

哪种方法最好?是否可以使用 mongoose 本身进行剪切,或者我应该在使用 PostModel.find() in success callback 检索文本后剪切文本?

您可以为此使用虚拟机。来自 docs:

Virtuals are document properties that you can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combining fields.

在你的情况下,你可以这样使用它:

var PostSchema = new mongoose.Schema({
    text : {type : String, default: ''},
    created_at : Date
});

PostSchema.virtual('truncated_text').get(function() {
  return this.text.substring(0, 150);
});

var PostModel = mongoose.model('PostModel', PostSchema);

那你可以用Post#truncated_text代替Post#text,例如:

Post.findOne({}, function(err, post) {
    console.log(post.truncated_text);
});

虚拟字段不会保存到数据库中,每次更新text字段时都会更新。