1

I have a case where i need to select only one document from the collection using mongoose

In mongo shell we use it as

db.user.find().limit(1)

{
"_id": "56fc22f625311b661becefb5",
“activities”: [...],
"lastName": “patrick”,
"firstName": "John”,
"city": “Chennai”,
"state": “TAMILNADU”,
"rollnumber": "123456789"
}

How to do it using mongoose, i have to select only particular field like rolenumber,state not all the fields

i tried it as

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/connector', function(err){
if(err) throw err
});
var Schema = mongoose.Schema;
var userSchema = new Schema({rollnumber : Number});
module.exports = mongoose.model('user', userSchema,'user');
var a = user.find().limit(1);
return a;
questionar
  • 274
  • 2
  • 18
  • posiible duplicate of https://stackoverflow.com/questions/14644545/random-document-from-a-collection-in-mongoose – Deepak Jul 31 '19 at 10:37

1 Answers1

0

As the Mongoose documentation says (http://mongoosejs.com/docs/queries.html):

Any model method which involves specifying query conditions can be executed two ways:
When a callback function:
- is passed, the operation will be executed immediately with the results passed to the callback.
- is not passed, an instance of Query is returned, which provides a special query builder interface.

So I suggest you to try something like this, with a callback function:

let user = mongoose.model('user', userSchema);
module.exports = user;    

user.find({}, 'rolenumber state')
    .limit(1)
    .exec((err, a) => {
        if (err) console.log(err);
        return a;
    });

Not sure for the random side of you question.

TGrif
  • 5,725
  • 9
  • 31
  • 52