当原始对象和set变量具有值时,未定义的声明结果

时间:2017-11-22 19:19:18

标签: javascript node.js postman

我使用node.js和Postman来POST函数/test。我将字段结果存储到toChange

  

想要设置:toChange.transaction.signature = element.transaction.signature;

toChange变量具有值,element.transaction.signature具有值。但是,当我定义toChange.transactiontoChange.transaction.signature时,声明会返回undefined。为什么会这样?我该如何解决?

(在server.js中使用过的部分):

logServer.post('/test', (req,res) => {
    console.log('starting test');
    let assetID = req.jwtPayload.assetID;
    logDB.collection('logs').find({"transaction.assetID" : assetID}).toArray( (err, result) => {

        if(err){
            console.log("Err : "+err.message);
            db.close();
            respondWithJSON(500,500,err.message,res);
            return; 
        }

        result.forEach(function(element, index, array) {

        let toChange = result.filter(function(e){return e._id === element._id});  //**HERE
        console.log('toChange', toChange);
        console.log('element.transaction.signature', element.transaction.signature);
        console.log('element.transactionSignature', element.transactionSignature);
        console.log('toChange.transaction', toChange.transaction); //**HERE

        //toChange.transaction.signature = element.transaction.signature; //**HERE
        //console.log('toChange.transaction.signature', toChange.transaction.signature);
        });
    });     
        res.status(200).send('hello, I am Log test');
});

(console.log输出):

[stdout] starting test
[stdout] toChange [ { _id: 1511359949,
[stdout]     transaction: 
[stdout]      { actor: 'patman',
[stdout]        type: 'Upload',
[stdout]        assetName: 'benten40.txt',
[stdout]        assetOwner: 'patman',
[stdout]        signature: 'c7ac2d40-c41c-4cd6-88ed-51c309114f40',
[stdout]        timeStamp: '2017-11-22T14:12:29.000Z',
[stdout]        result: 'Success' },
[stdout]     transactionSignature: '632e61b5-a022-482c-a4c5-4940b53cb922' } ]
[stdout] element.transaction.signature c7ac2d40-c41c-4cd6-88ed-51c309114f40
[stdout] element.transactionSignature 632e61b5-a022-482c-a4c5-4940b53cb922
[stdout] toChange.transaction undefined

1 个答案:

答案 0 :(得分:0)

Array.prototype.filter()返回一个数组,因此您应该toChange[ 0 ].transaction。但是,如果您只想要一个元素,请使用Array.prototype.find()

此外,_id可能是ObjectID类型的对象。对象的相等运算符只有在它们是同一个对象时才返回true:

const obj1 = { a: 12 };
const obj2 = { a: 12 }; 
const obj3 = obj1;

obj1 === obj2; // false
obj1 === obj3; // true

您可以手动拨打双方toString()或使用e._id.equals( element._id )

话虽这么说,_id个对象在此特定示例中是同一个对象,因为eelement来自{{1} }和results是唯一的。 _ide也是同一个对象。