【问题标题】:find results of attributes in mongodb are always undefined在 mongodb 中查找属性的结果总是未定义的
【发布时间】:2013-02-17 03:24:22
【问题描述】:

这方面我真的很需要帮助。我正在使用带有 mongodb 和 mongoose 的 node.js。到目前为止,我已经设法创建了一个模式并将其保存到我的数据库中。

var Bericht = new Schema({
    name     : String
  , mail     : String
  , betreff  : String
  , inhalt   : String
  , datum    : Date
});
var Bericht = mongoose.model('Bericht', Bericht);

我有一个 html 公式,我可以用 misc 进行传输。字段数据,通过查询字符串我将它们转换为可读字符串

var bericht_data = { 
name: tempo.Name
, mail: tempo.Mail
, betreff: tempo.Betreff
, inhalt: tempo.Inhalt
};
var testoro = new Bericht(bericht_data);
testoro.save(function (err) {
  if (!err) console.log('Success!');
}); 

所以 tempo.Name 例如是一个字符串,它也成功地保存了它。 到目前为止,我可以将这个公式中的所有数据保存到我的 mongodb 中。

现在的问题是:我希望将数据作为字符串返回以处理动态 html。 要将信息输入我的控制台,我使用

Bericht.find(
{},
{ '_id': 0},
        function(err, docs) {
        if (!err){ 
               console.log(docs);
          // process.exit();
                  }
        else { throw err;}
        }
);

控制台为我提供了曾经保存在我的架构 Bericht 中的所有数据,不包括长 _id 的东西。样本输出: [ { name: 'Hans', mail: 'hans@wurst.de', betreff: 'I lost my wurst', inhalt: '看看我,我太棒了' } ] 这只是一个,通常会有大量的数据。 现在的想法是仅将名称提取到像“Hans”这样的字符串中。我想把这个名字变成一个变量,但是这似乎是不可能的! 我试过了

Bericht.find(
{},
{ '_id': 0},
        function(err, docs) {
        if (!err){ 
               console.log(docs.name);
          // process.exit();
                  }
        else { throw err;}
        }
);

但我得到的只是“未定义”。感谢您的帮助!

【问题讨论】:

  • 我必须承认我不使用猫鼬,但我知道 JS。如果尝试的话,Mongoose 是否真的打印出一个数组而不是某种游标对象:docs[0].name

标签: node.js mongodb mongoose


【解决方案1】:

看看Mongoose QueryStreams。我自己没有使用过,但我修改了他们的示例代码以适合您的模型,让您了解它在实践中的工作方式:

var stream = Bericht.find().stream()
  , names = []
  , i;

function closeHandler() {
  console.log(JSON.stringify(names));
};

stream.on('data', function (doc) {
  if (doc.name) {
    names.push(doc.name);
  }
})

stream.on('error', function (err) {
  // handle err
})

stream.on('close', closeHandler)

【讨论】:

  • AAAA 太棒了!我已经想到我必须转移到其他功能,非常感谢您将我引导到 QueryStreams!
【解决方案2】:

Mongoose find 返回一个文档数组,因此您应该尝试以下操作:

Bericht.find(
 {},
 { '_id': 0},
    function(err, docs) {
     if (!err){
        for(var i=0; i<docs.length; i++)
        {
           console.log(docs[i].name);
        }
      // process.exit();
     }
    else { throw err;}
    }
);

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 2016-02-07
    • 2019-05-27
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多