我在这段代码中有一个小问题:
router.get("/validate/:nickname/:token", (req, res) => {
const nickname = req.params.nickname;
const token = req.params.token;
TmpUser.find({nickname: nickname, _id: token})
.select("nickname email password")
.exec()
.then(result => {
if (result.length === 1) {
console.log(result + " ||| email => " + result.email + " password => " + result.password);
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: result.email,
password: result.password,
level: 0,
nbcommands: 0
})
user
.save()
.then(result => {
res.status(200).json({
message: "user created",
user: user
});
});
} else {
res.status(404).json({
message: "user not found",
});
}
});
});
在console.log的这段代码中,对象的结果已定义,但例如,当我要访问result.email时,它说它是未定义的。
这是console.log(result)btw的结果:
{ _id: 5c1a7ee340f7876b08078ac2,
nickname: 'morgan',
email: 'morgan@gmail.com',
password:
'$2b$10$YNGN.QbtIqKn6ECA/7EazOGC4D/Bq.1hRGIQLHXmcq529SHs0K.ia' }
你能帮我吗? 谢谢!
答案 0 :(得分:1)
这是因为MongoDB将以对象数组的形式返回数据。
您已经使用result.length === 1
检查了结果是否为空数组。尝试使用下面给出的索引号
const user = new User({
_id: new mongoose.Types.ObjectId(),
email: result[0].email, // use index[0] to get first element
password: result[0].password, // same here too
level: 0,
nbcommands: 0