Cách đơn giản nhất mà không cần chỉnh sửa bất kỳ mã Meteor nào là sử dụng mongodb của riêng bạn. mongodb.conf
của bạn sẽ trông giống như thế này (trên Arch Linux, nó được tìm thấy tại /etc/mongodb.conf
)
bind_ip = 127.0.0.1
quiet = true
dbpath = /var/lib/mongodb
logpath = /var/log/mongodb/mongod.log
logappend = true
setParameter = textSearchEnabled=true
Dòng chính là setParameter = textSearchEnabled=true
, như nó nói, cho phép tìm kiếm văn bản.
Bắt đầu mongod
lên
Yêu cầu sao băng sử dụng mongod
của bạn không phải của riêng nó bằng cách chỉ định MONGO_URL
biến môi trường.
MONGO_URL="mongodb://localhost:27017/meteor" meteor
Bây giờ, giả sử bạn có bộ sưu tập có tên là Dinosaurs
đã khai báo nói trong collections/dinosaurs.js
Dinosaurs = new Meteor.Collection('dinosaurs');
Để tạo chỉ mục văn bản cho bộ sưu tập, hãy tạo tệp server/indexes.js
Meteor.startUp(function () {
search_index_name = 'whatever_you_want_to_call_it_less_than_128_characters'
// Remove old indexes as you can only have one text index and if you add
// more fields to your index then you will need to recreate it.
Dinosaurs._dropIndex(search_index_name);
Dinosaurs._ensureIndex({
species: 'text',
favouriteFood: 'text'
}, {
name: search_index_name
});
});
Sau đó, bạn có thể hiển thị tìm kiếm thông qua Meteor.method
, ví dụ trong tệp server/lib/search_dinosaurs.js
.
// Actual text search function
_searchDinosaurs = function (searchText) {
var Future = Npm.require('fibers/future');
var future = new Future();
Meteor._RemoteCollectionDriver.mongo.db.executeDbCommand({
text: 'dinosaurs',
search: searchText,
project: {
id: 1 // Only take the ids
}
}
, function(error, results) {
if (results && results.documents[0].ok === 1) {
future.ret(results.documents[0].results);
}
else {
future.ret('');
}
});
return future.wait();
};
// Helper that extracts the ids from the search results
searchDinosaurs = function (searchText) {
if (searchText && searchText !== '') {
var searchResults = _searchEnquiries(searchText);
var ids = [];
for (var i = 0; i < searchResults.length; i++) {
ids.push(searchResults[i].obj._id);
}
return ids;
}
};
Sau đó, bạn chỉ có thể xuất bản các tài liệu đã được tìm kiếm trong 'server / Publishers.js'
Meteor.publish('dinosaurs', function(searchText) {
var doc = {};
var dinosaurIds = searchDinosaurs(searchText);
if (dinosaurIds) {
doc._id = {
$in: dinosaurIds
};
}
return Dinosaurs.find(doc);
});
Và đăng ký phía máy khách sẽ trông giống như thế này trong client/main.js
Meteor.subscribe('dinosaurs', Session.get('searchQuery'));
Đạo cụ để Timo Brinkmann có dự án musiccrawler của ai là nguồn của hầu hết kiến thức này.