Ryan
Ryan

Reputation: 1019

How to convert the array obtained from the find function in mongoose to be an array of a single type (e.g string)

I have a simple schema:

  var mongoose = require('mongoose');
 var Schema = mongoose.Schema;

 var emoji = new Schema({


 url: { type: String, required: true, unique: true }



  });


 var ModelClass = mongoose.model('emojis', emoji);
 module.exports = ModelClass;

/////in a separate file

 Emoji.find({ }, 'url', function(err, users){


  console.log(users.url)

 });

I call Emoji.find to find all the urls that are saved in mongo. The result I'm given back is:

enter image description here

How can I make it such that the array only says ['dog', 'cat', 'horse', 'toucan', 'zebra']. If there's no direct way to do it in the query, what's the workaround. I need the array to be fully strings in order to filter another array of strings (e.g ['pigeon', 'squirrel']).

Upvotes: 1

Views: 275

Answers (1)

Kiran Sunkari
Kiran Sunkari

Reputation: 301

yo can try distinct:

emoji.find().distinct('url', function(error, url) {
    // url is an array of all ObjectIds
});

Upvotes: 1

Related Questions