我有一個被定義為的架構:
const postSchema = new mongoose.Schema({
url: String,
description: String,
created_date: Date
});
Post = mongoose.model('Post', postSchema)
}
我有一個路由器可以發布并將其保存到資料庫中。
router.post('/posts', async function (req, res, next) {
try {
const newPost = new Post({
url: req.body.url,
description: req.body.description,
current_time: req.body.created_date
});
await newPost.save();
res.json('status: success!')
console.log(Post)
console.log(newPost)
} catch (error) {
res.json("status: error! " error "could not connect to the database");
}
})
我可以在我的 mongdb 中看到資料,當我通過輸入輸入新資料時它會填充。
使用下面的代碼,當我控制臺記錄 Post.find(); 時列印出 id、url 和描述;
router.get('/posts', async function (req, res, next) {
let allPosts = await Post.find();
console.log(allPosts)

我的問題是,如何從中獲取 url 資料?我試過使用:
Post.url
req.query.paramNames
我正在查看 Mongodb 檔案,但我遺漏了一些東西。
uj5u.com熱心網友回復:
Post.find({},{url:1,description:1})
你做錯了。第二個引數應該有助于選擇您需要查找的欄位。這將回傳一個陣列。如果您正在查找特定檔案,您需要將其更改為 findOne 并在第一個引數上添加搜索欄位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339362.html
