[英]mongoose findByID returning undefined
當嘗試使用findById
從數據庫記錄數據時,我得到undefined
的返回值。
// Get single article
app.get('/article/:id', (req, res) => {
Article.findById(req.params.id, (err, article) => {
console.log(article);
return;
});
});
//Article Schema
let articleSchema = mongoose.Schema({
title: { type: String, required: true },
author: { type: String, required: true},
body: { type: String, required: true}
});
let Article = module.exports = mongoose.model('Article', articleSchema)
我查了一些東西,我讓它工作了,但我不確定這是否是正確的方法
所以我發現如果我使用findOne()
並傳入Article.id
我會得到我想要的結果,但這是正確的做事方式嗎?
我覺得article.id
應該由req.params.id
傳遞,但是當我將它傳遞給findOne()
我收到一條錯誤消息:
Error: Invalid argument to findOne(): 'article_id'
使用Article.findById(mongoose.Types.ObjectId(req.params.id)}, (err, article)...
因為您正在尋找對象 ID 而不是字符串。
我遇到了,我解決了。
const UserModel = require('../models/userModel')
exports.getUser = async(req, res) => {
const _id = req.params.id
try {
const user = await UserModel.findById(_id)
if (!user) {
return res.status(404).send()
}
res.status(201).send(user)
} catch (error)
{
res.status(500).send(error)
}
}
控制器/路由
router.get('/user/:id', userController.getUser)
型號
const mongoose = require('mongoose')
const validator = require('validator')
const User = mongoose.model('User', {
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
password: {
type: String,
required: true,
minlength: 7,
trim: true,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Password cannot contain "password"')
}
}
},age: {
type: Number,
default: 0,
validate(value) {
if (value < 0) {
throw new Error('Age must be a postive number')
}
}
}
})
module.exports = User
您是否從數據庫中提取了正確的 ID,在將您發送到 /article/:id 的鏈接上。 我遇到了同樣的問題,因為我之前在基本數組索引上學到了知識並轉移到了 MongoDB。 我只需要更新一個字符以包含'_id'而不是'id'的MongoDB語法的下划線。
在我的 HTML 渲染頁面上對我有用的正確代碼如下:
<a href={`/article/${article._id}`}>
我開始並給我一個未定義的結果如下:
<a href={`/article/${article.id}`}>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.