簡體   English   中英

將新字段和值推送到node.js中的json數組對象

[英]Push new field and value to json array object in node.js

我是node.js的新手。 我需要在jqgrid中顯示Name,但是我只將一個文檔的ID存儲到另一個文檔中。

我有2個文件,例如Student Master和Student Mark文件。 我必須在jqgrid中顯示標記詳細信息。 在標記文檔中,我存儲了學生證而不是姓名。 如何獲取名稱並將新對象發送到jqgrid?

我的代碼如下:

exports.getAllstudentsmark = function(req, callback)
{
    studentsmarks.find(function(error, studentsmarks_collection) {
      if( error ) callback(error)
      else {

        studentsmarks_collection.toArray(function(error, results) {
          if( error ) callback(error)
          else {
            newresult = results;
            for(i=0;i<results.length;i++)
            {
                newresult[i]['studentname'] = getStudentName(results[i].studentid);
            }
            console.log(newresult);
            callback(null, newresult)}
        });
      }
    });
}

var getstudentObjectId = function(id)
{
    return student.db.bson_serializer.ObjectID.createFromHexString(id);
}
var getStudentName = function(id)
{
    student.findOne({_id: getstudentObjectId (id)}, function(e, o){
console.log(o.name);
        return o.name;
    });
}

newresult [i] ['studentname']總是未定義。 但是,如果我登錄到getStudentName函數,則可以得到getStudentName函數的答案。

我的回調函數只會遇到此問題。 如何輕松解決並獲得我的結果。 請幫助任何一個。

在您的for循環中嘗試一下

newresult.push({'studentname': getStudentName(results[i].studentid) });

解釋:您訪問newresult[i]時不存在,因此無法訪問它的studentname字段

這里的問題是您沒有在數組中設置用戶名,而是將student.findOne的返回值設置為數組,因為這是一個異步方法。 也許試試這個東西

exports.getAllstudentsmark = function(req, callback)
{
  studentsmarks.find(function(error, studentsmarks_collection) {
  if( error ) callback(error)
  else {

    studentsmarks_collection.toArray(function(error, results) {
      if( error ) callback(error)
      else {
        newresult = [];
        for(i=0;i<results.length;i++)
        {
            getStudentName(results[i].studentid, function (studentName) {
               newresult.push({studentname: studentName});
            })
        }
        console.log(newresult);
        callback(null, newresult)}
    });
  }
});
}

var getstudentObjectId = function(id)
{
    return student.db.bson_serializer.ObjectID.createFromHexString(id);
}
var getStudentName = function(id, callback)

{
    student.findOne({_id: getstudentObjectId (id)}, function(e, o){
console.log(o.name);
        callback(o.name);
    });
}

希望對您有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM