我有以下架构:
var PostModel = mongoose.model('PostModel', {
text : {type : String, default: ''},
created_at : Date
});
text
字段可能很长(大约 1000 个字符)。当我在我的帖子列表页面上查询帖子时,我需要查询所有帖子,并将 text
字段剪切为仅 150 个字符。
哪种方法最好?是否可以使用 mongoose 本身进行剪切,或者我应该在成功回调中使用 PostModel.find() 检索文本
后剪切文本?
最佳答案
您可以为此使用虚拟机。来自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);
});
虚拟字段不会保存到数据库中,每次更新文本
字段时都会更新。
关于node.js - 如何在 Mongoose 中查找文档时剪切文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29479401/