使用猫鼬,如果我试图找到使用db.model()像猫鼬文档存储在数据库中的文档建议,我没有得到任何结果:(查找不与猫鼬4.6工作。*
不过,如果我使用db.collection()。find()方法,我得到的结果。
这是为什么?又会有怎样使用下面?
在示例代码的最佳方法app.js
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(config.database.url); // database configuration
app.locals.db = mongoose.connection;
app.locals.db.on('error', function(msg){
console.log("db connection failed", msg);
});
app.locals.db.once('open', function(){
console.log("db connected successfully");
});
在路由 - > person.js
var Person = require('Person');
router.post('/search', function(req, res) {
var person = new Person(req.app.locals.db);
person.getPerson(req.body.name, function(found, docs) {
if (found === false)
res.render('pageTpl', { results: 'person not found' });
else
res.render('pageTpl', { results: docs });
});
在Person.js
// schema here returns new mongoose.Schema({ fields : types })
const personSchema = require('./schemas/personSchema');
function Person(db) {
this.db = db;
}
Person.prototype.getPerson = function(term, callback) {
var Person = this.db.model('people', personSchema);
var q = Person.find({ name: /^term/ }).sort('age').limit(2);
q.exec(function(err, results) {
if (err) return callback (false, err);
// This returns [] results
console.log(results);
callback(true, results);
});
});
module.exports = Person;
在数据库中,我有一个名为:people的集合。我假设并猜测在this.db.model('people'...)中,人们是数据库中集合的名称?如果这是正确的:我不能使用我想要的任何名字? –