I have a schema that's been defined as:
const postSchema = new mongoose.Schema({
url: String,
description: String,
created_date: Date
});
Post = mongoose.model('Post', postSchema)
}
and I have a router that posts and saves it to the database.
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");
}
})
I can see the data in my mongdb and it populates when I enter new data through inputs.
With the code below, the id, url, and description print out when I console log the Post.find();
router.get('/posts', async function (req, res, next) {
let allPosts = await Post.find();
console.log(allPosts)
My question is this, how do I get just the url data out of this? I've tried using:
Post.url
req.query.paramNames
I'm looking through Mongodb documentation but I'm missing something.
CodePudding user response:
Post.find({},{url:1,description:1})
You are doing it wrong. The second parameter should help in selecting the fields you need to find. This will return an Array. If you are looking for specific document you need to change it to findOne and add the search field on first parameter.