我剛開始玩貓鼬和蒙戈。我有以下代碼:Mongoose find(),如何訪問結果文檔?
var ninjaSchema = mongoose.Schema({
name: String,
skill: Number
});
var Ninja = mongoose.model('Ninja',ninjaSchema);
module.exports = {
init : function(){
console.log('Connecting to database');
mongoose.connect('mongodb://localhost/mydb');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
console.log('Successfully connected!');
});
},
createNinja : function(name,skill){
var n = new Ninja({name:name,skill:skill});
n.save(function(err,n){
if (err)
console.log('saving failed');
console.log('saved '+ n.name);
});
},
getNinjas : function(){
var res = null;
res = Ninja.findOne({},'name skill',function(err,docs){
if (err)
console.log('error occured in the query');
return 'ninja name: '+docs.name+' ninja skill: '+docs.skill;
});
return res;
}
將條目添加到數據庫沒有問題,但我在檢索它們時遇到問題。我對整個事情是如何工作感到困惑。我的理解如下:
有一些模式,就像oop中的類一樣,只是數據庫中記錄的藍圖。模型是一個記錄,好吧,也許更多一點,因爲我看到你可以在模型中添加一個方法。那麼......我真的不明白如何使用它們。你能給我一個線索是什麼嗎?
返回到主題:當發出find命令時,它會調用匿名函數,文檔應該是正確的結果?現在我該如何訪問它們?由於現在如果我登錄的資源,我得到以下幾點:
{ options: {},
safe: undefined,
_conditions: {},
_updateArg: {},
_fields: { name: 1, skill: 1 },
_geoComparison: undefined,
op: 'findOne',
model:
{ [Function: model]
base:
{ connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: {} },
modelName: 'Ninja',
model: [Function: model],
db:
{ base: [Object],
collections: [Object],
models: {},
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'mydb',
options: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: true,
_events: [Object],
db: [Object] },
schema:
{ paths: [Object],
subpaths: {},
virtuals: [Object],
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: [],
options: [Object],
_events: {} },
options: undefined,
collection:
{ collection: [Object],
opts: [Object],
name: 'ninjas',
conn: [Object],
queue: [],
buffer: false } } }
另外,如果我用Ninja.find(...,function(err,docs){ ... })
我怎麼走線槽的文檔?或者我如何檢索我的記錄?
你丫打我的名字它。我爲你制定了一個很好的答案,但你明白了。您需要傳遞迴傳結果。 – numbers1311407 2013-04-06 15:29:26