0
我通過所有的集合試圖循環中貓鼬底層連接:我如何遍歷集合中的貓鼬
var chai = require('chai'),
expect = chai.expect,
mongoose = require('mongoose'),
db = mongoose.connection;
describe('Blog Tests', function() {
before(function() {
console.log('before called');
db.on('error', console.error);
mongoose.connect('mongodb://localhost/mydb', function(err){
if(err)console.err(err);
// never loops through collections at this point!
for (var i in mongoose.connection.collections) {
console.log(mongoose.connection.collections[i]);
// will drop collection here
}
});
});
after(function(){
console.log('after called');
if(db.db._state === 'connected'){
console.log('closing db');
db.close();
}
});
it('Can add a blog post', function (done) {
db.on('open', function(){
var blogPostSchema = new mongoose.Schema({
id: mongoose.Schema.ObjectId,
title: {type: String, required: true},
content: {type: String},
tags: []
}),
BlogPost = mongoose.model('BlogPost', blogPostSchema),
blogPost = new BlogPost({
title: 'Hello World',
content: 'Lorem baby',
tags: [{"tag": "tests"},{"tag": "mocha"}, {"tag": "chai"}]
});
blogPost.save(function(err, saved){
if (err) console.error(err);
expect(saved.title).is.equal('Hello World');
done();
});
});
});
});
但它永遠不會返回集合 - 他們DEFS存在,它只是返回空物體;不是一個空陣列。
任何人都可以發現這個愚蠢的錯誤嗎?
更新爲每Gergo建議,但仍然沒有顯示的集合:
var chai = require('chai'),
expect = chai.expect,
mongoose = require('mongoose'),
db = mongoose.connection;
describe('Blog Tests', function() {
before(function (done) {
console.log('before called');
db.on('error', console.error);
mongoose.connect('mongodb://localhost/mydb', function(err){
if(err) return console.err(err);
// never loops through collections at this point!
for (var i in mongoose.connection.collections) {
console.log(mongoose.connection.collections[i]);
// will drop collection here
}
done();
});
});
after(function(done){
console.log('after called');
if(db.db._state === 'connected'){
console.log('closing db');
db.close();
done();
}
});
it('Can add a blog post', function (done) {
var blogPostSchema = new mongoose.Schema({
id: mongoose.Schema.ObjectId,
title: {type: String, required: true},
content: {type: String},
tags: []
}),
BlogPost = mongoose.model('BlogPost', blogPostSchema),
blogPost = new BlogPost({
title: 'Hello World',
content: 'Lorem baby',
tags: [{"tag": "tests"},{"tag": "mocha"}, {"tag": "chai"}]
});
blogPost.save(function(err, saved){
if (err) console.error(err);
expect(saved.title).is.equal('Hello World');
done();
});
});
});
感謝您的回覆Gergo,可惜mongoose.connection的回調函數內的mongoose.connection.collections仍然沒有按」 t獲取收藏並且連接已打開。我修改了上面的原始代碼。 - Chev 38分鐘ag – Chev
@Chev更新了我的答案。 –
似乎mongoose.connection.collections就像是貓鼬藏品的緩存 – Chev