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

Eri*_*rik 3 mongoose mongodb node.js

我有以下架构:

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

text字段可能很长(大约1000个字符).当我在帖子列表页面上查询帖子时,我需要查询所有包含剪切text字段的帖子,仅限150个字符.

这是最好的方法吗?是否可以通过使用猫鼬本身进行切割,还是应该在使用后检索文本PostModel.find() in success callback

vic*_*ohl 5

您可以使用虚拟机.来自文档:

虚拟是您可以获取和设置的文档属性,但不会持久保存到MongoDB.getter对于格式化或组合字段很有用.

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

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);
Run Code Online (Sandbox Code Playgroud)

然后你可以使用Post#truncated_text代替Post#text,例如:

Post.findOne({}, function(err, post) {
    console.log(post.truncated_text);
});
Run Code Online (Sandbox Code Playgroud)

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