如何返回Mongoose对象字段(在Module.exports函数中)

时间:2016-04-27 16:24:18

标签: javascript node.js mongodb module mongoose

所以我有以下代码:

var Mix = require('../models/mix');

module.exports = {
    mixTitle: function(mix_id) {
        return Mix.findOne({ 'mix_id' : mix_id }, 'title', function(err, mix){
          console.log(mix.title); // This correctly prints the title field
          return mix.title;
        });
    }
}

我导入了Mix模型,然后可以访问回调中的title字段,但有没有办法真正返回mix.title字符串值?目前我所得到的只是(我认为)查询原型..

Query {
  _mongooseOptions: {},
  mongooseCollection: 
   NativeCollection {
     collection: { s: [Object] },
     opts: { bufferCommands: true, capped: false },
     name: 'mixes',
     collectionName: 'mixes',
     conn: 
      NativeConnection {
        base: [Object],
        collections: [Object],
        models: [Object],
        config: [Object],
        replica: false,

...等

如何正确编写此导出函数以返回找到的Object的标题字段?

1 个答案:

答案 0 :(得分:1)

ArrayList<String> myArray = new ArrayList<>(); StringTokenizer stok = new StringTokenizer(s, "><"); while (stok.hasMoreTokens()) { String token = stok.nextToken(); // get and save in variable so it can be used more than once System.out.println(token); // print already extracted value // more code here if needed myArray.add(token); // use already extracted value } System.out.println(myArray); // prints list 是异步函数,你可以立即得到函数的结果。您可以传递Mix.findOne参数并获得结果,或者更好的解决方案 - 使用promises:

callback