我正在用nodejs建立遊戲0.6.18 expressjs 2.5.8和mongoose 2.6.7。Expressjs貓鼬發現嵌套嵌入式文件未定義
我試圖用貓鼬來存儲和檢索嵌入式文件。 考慮這個例子:
用戶模式
var User = module.exports = new Schema({
username: { type: String }
, characters: [Character]
, created: { type: Date, default: Date.now }
});
字符模式
var Character = module.exports = new Schema({
name: { type: String }
, spells: [Spell]
, created: { type: Date, default: Date.now }
});
拼寫模式
var Spell = module.exports = new Schema({
name: { type: String }
, created { type: Date, default: Date.now }
});
貓鼬
var db = mongoose.createConnection('mongodb://localhost/mygame');
mongoose.model('User', require('./models/user'));
mongoose.model('Character', require('./models/character'));
mongoose.model('Spell', require('./models/spell')
路線
app.get('/', function(req, res) {
var User = db.model('User')
, Character = db.model('Character')
, Spell = db.model('Spell')
, u = new User({username:'foo'})
, c = new Character({name:'bar'});
c.spells.push(new Spell({name:'fireball'}));
c.spells.push(new Spell({name:'frozenball'}));
u.characters.push(c);
u.save(function(e, s) {
User.find({username:'foo'}, function(err, success) {
console.error(err);
console.log(success);
});
});
});
控制檯輸出
null
[ { username: 'foo',
_id: 4fda2c77faa9aa5c68000003,
created: Thu, 14 Jun 2012 18:24:55 GMT,
characters: [ undefined ] } ]
它看起來像用戶文檔被正確保存和檢索貓鼬。但是,相關的嵌入式文檔是undefined。
我想確保我的文檔保存,所以我直接問到MongoDB的:
$ mongo mygame
> db.users.find({username:'foo'})
{
"username" : "foo",
"_id" : ObjectId("4fda2c77faa9aa5c68000003"),
"created" : ISODate("2012-06-14T18:24:55.982Z"),
"characters" : [
{
"name" : "bar",
"_id" : ObjectId("4fda2c77faa9aa5c68000004"),
"created" : ISODate("2012-06-14T18:24:55.986Z"),
"spells" : [
{
"name" : "fireball",
"_id" : ObjectId("4fda2c77faa9aa5c68000005"),
"created" : ISODate("2012-06-14T18:24:55.987Z")
},
{
"name" : "frozenball",
"_id" : ObjectId("4fda2c77faa9aa5c68000007"),
"created" : ISODate("2012-06-14T18:24:55.990Z")
}
]
}
]
}
正如你看到的,我的文件似乎正確保存到MongoDB的,但我無法檢索誰嵌入貓鼬。
我也嘗試過沒有嵌套的嵌入式拼寫文件,這將產生完全相同的問題。
編輯
@pat你是對的。如果我用正確的順序將所有模式直接放在同一個文件(例如main app.js)中,它就可以工作。
事實是,我想盡可能將每個模型保存在單獨的文件中(它們會增長很多)。
例如,我的用戶模型包含在一個名爲models/user.js的文件中,並且應該可以使用module.exports
如上所述訪問。
但是,當我嘗試將我的模型鏈接到另一個文件中的貓鼬時:mongoose.model('User', require('./models/user'));
mongoose find方法返回未定義的嵌入式文檔。
對於如何正確將我的貓鼬模型保存在單獨的文件中,您有什麼想法嗎?
謝謝。我的問題來自依賴性問題以及錯誤的文件結構。我最終通過ObjectIds加入我的模型而不是嵌入式文檔,這似乎更適合我的需求。 –