【问题标题】:Sails.js find records and store result into a varSails.js 查找记录并将结果存储到 var
【发布时间】:2015-06-23 11:59:46
【问题描述】:

我想查询 MongoDb,并将返回的记录保存到一个变量中,这是我在 Controller 中尝试的:

var projects= {};

Project.find({}).exec(function findProject(err, found){

       projects = found;
       console.log(found.length);

       while (found.length)
         console.log('Found Project with name ' + found.pop().name)
});

// 这将返回未定义

console.log(projects.length);

我做错了吗?

如何将 .find() 的结果传递给变量项目?

【问题讨论】:

    标签: javascript node.js mongodb callback sails.js


    【解决方案1】:

    你应该停止 pop() -ing 你的数组。 您的对象正在传递 by reference,而不是 by value。因此,当您从一个项目中删除项目时,您实际上会影响另一个项目。

    编辑:

    如果您仍有疑问,可以检查您的查询:

    Project.find({}).exec(function findProject(err, found){
         if (err) { // here
              console.log(err);
         } else if (found.length == 0){
              console.log("Nothing was found");
         } else {
              console.log(found);
         }
    });
    

    对象没有.length 属性,这就是你得到undefined 的原因。我假设你得到一个错误,这就是你的 found 参数不是数组的原因。

    【讨论】:

    • 这不起作用的是projects = found; 它是未定义的。如何将 .find() 的结果传递到变量项目中?
    • @Grimmy,抱歉耽搁了。请参考我的编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 2011-02-11
    • 2019-06-04
    相关资源
    最近更新 更多