我正在构建类似克隆的Twitter,并且试图构建搜索系统以对所有tweet数据执行常规文本查找。每条推文都存储了对作者的引用,因此在使用.find()
之前,我必须先调用populate。我尝试这样做无济于事:
const searchTerm = req.query.query;
Tweet.find()
.limit(10)
.populate("author")
.find( { $text: { $search: `${searchTerm}` } })
.then(data => {
res.json({ tweets: data });
})
.catch((err) => console.log(err));
这是Tweet
模型
const TweetSchema = new Schema({
content: {
type: String,
required: true,
},
category: {
type: String,
required: false,
},
comments: [Comment.schema],
author: { type: Schema.Types.ObjectId, ref: "user", required: true },
replies: {
type: Number,
default: 0,
},
likes: {
type: Number,
default: 0,
},
date: {
type: Date,
default: Date.now,
},
});
TweetSchema.index({ "$**": "text" });
module.exports = Tweet = mongoose.model("tweet", TweetSchema);