node.js - 访问 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,
})
解决方案
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,因为我发现它更容易,你可以将它转换为你的回调函数
我希望这有帮助
推荐阅读
- javascript - Vuetify v-btn 点击事件
- javascript - Javascript onoff按钮在聊天机器人中不起作用
- android - firebase 在未知 uid 后从 uid 获取价值
- java - Jackson 动态数据反序列化失败,
- java - java.library.path 中没有 rxtxSerial
- cucumber - Cucumber\Rest Assured:如何获取请求规格?
- sparql - 如何在 dbpedia 中获取 owl:sameas
- spring-boot - 在类型 [java.lang.String] 上找不到属性 [id]
- ios - Apple 拒绝了我的应用程序:UIRequiredDeviceCapabilities 键
- apostrophe-cms - 如何将最后三个添加的数据从子页面加载到主页