How to extract only certain data from a collection with Mongoose?
Clash Royale CLAN TAG#URR8PPP
How to extract only certain data from a collection with Mongoose?
I have a collection with only a name
and a number
. I would like to extract only the number out of it and change it / put it in a variable. How would I do either of those?
name
number
let dataSchema = new mongoose.Schema(
name: String,
views: Number
)
let Views = mongoose.model("View", dataSchema);
1 Answer
1
You can pass a second argument to the find() method indicating the fields that must be returned.
Views.findOne(, views: true , (err, doc) =>
if (!err)
// doc.views
);
Edit
There are several other options for limiting the returned fields with mongoose
Pass space-separated field names:
Views.findOne(query, "views", callback)
Using select()
method:
select()
Views.findOne(query).select('views').exec(callback);
Views.findOne(query).select( views: 1 ).exec(callback);
@icyfox I've added two new options to the answer you can try
– Shant Marouti
Aug 22 at 14:59
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
works the same as the old one did, when I console.log the variable it returns the entire object and not just the views property...
– icyfox
Aug 11 at 16:50