Mongoose find(),如何访问结果文件? [英] Mongoose find(), how to access the result documents?

查看:174
本文介绍了Mongoose find(),如何访问结果文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始玩mongoose和mongo。我有以下代码:

  var ninjaSchema = mongoose.Schema({
name:String,
技能:数量
});

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);
});
},
getNin​​jas:function(){
var res = null;
res = Ninja.findOne({},'name skills',function(err,docs){
if(err)
console.log('query occurred in the query');
return'ninja name:'+ docs.name +'ninja skill:'+ docs.skill;
});

return res;
}

在数据库中添加条目没有问题,但检索它们时遇到问题。我对整个事情的工作有点困惑。我的理解如下:



有一些模式,它们类似于oop中的类,所以只是数据库中记录的蓝图。该模型是一个记录,好的,也许多一点,因为我看到你可以添加一个方法到模型。嗯...我真的不明白如何使用它们。你能给我一个线索吗?



回到主题:发出find命令时,它调用匿名函数,文档应该是结果吗?现在我如何访问它们?从现在起,如果我登录了res,我得到以下内容:

  {options:{},
safe:undefined,
_conditions:{},
_updateArg:{},
_fields:{name:1,skill:1},
_geoComparison:undefined,
op:'findOne ',
模型:
{[功能:模型]
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],
子路径:{},
virtuals:[Object],
嵌套:{},
继承:{},
callQueue:[],
_indexes :[],
方法:{},
statics:{},
树:[对象],
_requiredpaths:[],
选项:[对象] ,
_events:{}},
选项:未定义,
集合:
{collection:[Object],
opts:[Object],
名称:'ninjas',
conn:[Object],
queue:[],
buffer:false}}}

另外如果我使用 Ninja.find(...,function(err,docs){...})我该怎么走文档?或者如何检索我的记录?

解决方案

我发现了错误。更多的是一个概念性的:我正在处理异步调用,并尝试从另一个函数返回结果,并且不知道它将执行什么时候。那么,我发出什么是请求执行db查询并返回结果,结果是null。这段代码:

  getNin​​jas:function(){
var res = null;
Ninja.find({},'name skill',function(err,docs){
if(err)
console.log('在数据库中发生错误');
console.log(docs);
});
return res;
}

返回null,但是! console.log(docs)打印到控制台中数据库中的所有值,我正在尝试做什么。现在我需要进行更改,很可能会传递一个回调,这将在收到结果时执行。



随着更改代码如下所示:

  getNin​​jas:function(res){
var twisted = function(res){
return function(err,data ){
if(err){
console.log('error occured');
返回;
}
res.send('我的忍者是:\\\
');
console.log(data);
}
}

Ninja.find({},'名字技能',扭曲(res));
}

所以这样我可以传递响应对象,所以我可以发送我的忍者的名字:)


I just started playing with mongoose and mongo. I have the following code:

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;
}

There is no problem in adding entries to the database but I have problems retrieving them. I am a bit confused about how the whole thing works. My understanding is the following:

There are the schemas, which are like classes in oop, so just a blueprint for a record in the database. The model is a record, OK, maybe a bit more, since I saw that you can add a method to the model. Well... I don't really understand how to use them. Can you give me a clue what really are they?

Back to the subject: When issuing the find command, it calls the anonymous function and docs should be the result right? Now how do I access them? Since now if I log the res I get the following:

{ 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 } } }

Also if I use Ninja.find(...,function(err,docs){ ... }) how do I go trough the docs? Or how do I retrieve my records?

解决方案

I've found the fault. It was more of a conceptual one: I am dealing with asynchronous calls and am trying to return the result from another function and don't know when it will execute. So what happens is I make the request that the db query be executed and return the result, which turns out to be null. This code:

getNinjas : function(){
    var res = null;
    Ninja.find({},'name skill',function(err,docs){
        if (err)
            console.log('error occured in the database');
        console.log(docs);
    });     
    return res;
}

returns null, but! the console.log(docs) prints to the console all the values from the database, what I was trying to do. Now I need to make changes, most likely pass a callback which will be executed upon the receiving of the results.

With the changes the code looks like this:

getNinjas : function(res){
    var twisted = function(res){
        return function(err, data){
            if (err){
                console.log('error occured');
                return;
            }
            res.send('My ninjas are:\n');
            console.log(data);
        }
    }

    Ninja.find({},'name skill',twisted(res));
}

So like this I am able to pass the response object so I can send the name of my ninjas :)

这篇关于Mongoose find(),如何访问结果文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆