Javascript 将新字段和值推送到node.js中的json数组对象

Javascript 将新字段和值推送到node.js中的json数组对象,javascript,jquery,node.js,Javascript,Jquery,Node.js,我是node.js的新手。我需要在jqgrid中显示名称,但我只将一个文档的id存储到另一个文档中 示例 我有两个文件,如学生硕士和学生分数文件。我必须在jqgrid中显示标记详细信息。在mark文档中,我存储了学生id而不是姓名。如何获取名称并将新对象发送到jqgrid 我的代码如下: exports.getAllstudentsmark = function(req, callback) { studentsmarks.find(function(error, studentsmar

我是node.js的新手。我需要在jqgrid中显示名称,但我只将一个文档的id存储到另一个文档中

示例

我有两个文件,如学生硕士和学生分数文件。我必须在jqgrid中显示标记详细信息。在mark文档中,我存储了学生id而不是姓名。如何获取名称并将新对象发送到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;
    });
}
exports.getAllstudentsmark=函数(请求,回调) { find(函数(错误,studentsmarks\u集合){ 如果(错误)回调(错误) 否则{ StudentsMark_collection.toArray(函数(错误、结果){ 如果(错误)回调(错误) 否则{ newresult=结果;
对于(i=0;i在
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);
    });
}
exports.getAllstudentsmark=函数(请求,回调) { find(函数(错误,studentsmarks\u集合){ 如果(错误)回调(错误) 否则{ StudentsMark_collection.toArray(函数(错误、结果){ 如果(错误)回调(错误) 否则{ newresult=[];
对于(i=0;iIt得到的错误类似于ReferenceError:赋值中的左侧无效