首页 > 解决方案 > 访问 userSchema(NodeJs 和 MongoDB)中的事务时,我得到“未定义”作为输出

问题描述

我希望输出为,它应该console.log()在我的命令提示符下进行交易。它只打印userSchema接受交易的所有对象。它正在打印“未定义”

[nodemon] 1.18.9
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node server.js`
Running on port 3000
Connection established
[nodemon] restarting due to changes...
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
 Running on port 3000
Connection established
5c4b294efb654f1770522264
{ _id: 5c4b294efb654f1770522264,
  email: 'dev@dev.com',
  username: 'username',
  password:
   'MY_SECRET_PASSWORD',
  privateKey:'MY_PRIVATE_KEY',
  __v: 0 }
undefined
POST /api/getTransactions 200 264.266 ms - -

这是 POST 路线

router.post('/getTransactions', function (req, res) {
    userId = req.body._id
    console.log(userId)
    //console.log(process.env.NODE_ENV)
    User.findOne({ _id: userId }, function (err, user) {
        console.log(user)

        if (user) {
            console.log(user.transactions)
            res.send(user.transactions)
        } else {
            console.log(err)
        }

    })
})

这是用户架构

var TransactionSchema = new Schema({
       time: {
           type: String
    },
    date : {
        type: String
    },
    transactionType : {
        type: String
    },
    email : {
        type: String
    },
    amount: {
        type: String
    },
    txHash:{
        type: String
    }
})

var UserSchema = new Schema({
    username: {
        type: String
    },
    email: {
        type: String,
    },
    password: {
        type: String
    },
    ethAddress: {
        type: String
    },
    privateKey: {
        type: String
    },
    transactions: TransactionSchema,
})

标签: node.jsmongodbmongoose

解决方案


var TransactionSchema = new Schema({
   time: {
       type: String
  },
  date : {
    type: String
  },
  transactionType : {
    type: String
  },
  email : {
    type: String
  },
  amount: {
    type: String
  },
  txHash:{
    type: String
  }
})

var UserSchema = new Schema({
  username: {
    type: String
  },
  email: {
    type: String,
  },
  password: {
    type: String
  },
  ethAddress: {
    type: String
  },
  privateKey: {
    type: String
  },
  transactions: [
    type: mongoose.Schema.Types.ObjectId,
    ref: 'TransactionModel' // this should be the name of your 
    // transactions model
    }
  ]
})

那么你的查询应该是

User.findOne({ _id: userId })
.populate('transactions')   
.then(user => {
  console.log(user)
})
.catch(e => {
  consoel.log('error')
});

请我使用promise,因为我发现它更容易,你可以将它转换为你的回调函数


我希望这有帮助


推荐阅读