在定义过滤嵌入式文档字段的静态查询时,我遇到了与连接相关的错误。我尝试将嵌入文档分离到单独的架构文件中,但没有解决问题。有任何想法吗?
错误如下:
C:\development_GIT\myproject\app\models\mymodel.js:40
this.find({ text.lang_code: langCode }).sort('text.name').exec(callback);
^
Error: Trying to open unclosed connection.
at NativeConnection.Connection.open (C:\development_GIT\myproject\node_
modules\mongoose\lib\connection.js:205:15)
at Mongoose.connect (C:\development_GIT\myproject\node_modules\mongoose
\lib\index.js:156:15)
at Object.<anonymous> (C:\development_GIT\myproject\server.js:13:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at repl:1:1
{ text.lang_code: langCode }
在以下模型中使用过滤器选项时会启动错误。如果我不使用嵌入式文档并尝试过滤例如{ _id: langCode }
它不会引发错误。
//MyModel.js located at ./app/models
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MyModelSchema = new Schema({
name: { type: String, trim: true },
text: [{ name: String, lang_code: String }]
});
MyModelSchema .static({
findByLangCode : function(langCode, callback) {
this.find({ text.lang_code: langCode }).sort('text.name').exec(callback);
}
});
mongoose.model('MyModel', CategorySchema);
我的主文件 server.js 的第一行是:
//server.js
var express = require('express');
var env = process.env.NODE_ENV || 'development';
var config = require('./config/config')[env];
var mongoose = require('mongoose');
var fs = require('fs');
require('express-namespace');
mongoose.connect(config.db);
// Bootstrap models
fs.readdirSync(__dirname + '/app/models').forEach(function (file) {
if (~file.indexOf('.js')) require(__dirname + '/app/models/' + file)
});