razorbeard
razorbeard

Reputation: 2944

How to fetch individual properties of a mongoose Model?

I've just started playing with mongoose today after reading The Little MongoDB book. I'm quite new to this, so far I already know how to query my collections from mongoose and find documents based on their properties, but what I want to find out is actually how to display just one property of a document for each document in the collection, say, in an Express res.send(). Just as a learning experiment, if you will.

I've coded this snippet in CoffeeScript:

express = require 'express'
app = express()
http = require 'http'
server = http.createServer app
mongoose = require 'mongoose'

mongoose.connect 'localhost', 'linkreferrers'

# ## Ignore these configurations for now
# app.configure ->
#   app.set 'views', __dirname + '/views'
#   app.set 'view engine', 'jade'

linkSchema = new mongoose.Schema {
    referer: 'string'
}

Link = mongoose.model 'Link', linkSchema

app.get '/', (req, res) ->
    # Fetch the HTTP Referer from the visitor's browser, store it in the database, display a list of referers
    refererdata = req.get 'Referer'
    if refererdata?
        link = new Link {referer: refererdata}
        do link.save
    Link.find (err, links) ->
        console.log err if err
        res.send links

server.listen 5000

This sends the following data to the user's browser:

[
  {
    "referer": "http://fiddle.jshell.net/_display/",
    "_id": "50f0fdcb75d2543b38000001",
    "__v": 0
  },
  {
    "referer": "http://fiddle.jshell.net/_display/",
    "_id": "50f18b0c95e3182a3a000001",
    "__v": 0
  },
  {
    "referer": "http://fiddle.jshell.net/_display/",
    "_id": "50f18b58040ac5413a000001",
    "__v": 0
  }
]

How would I go about sending only the referer parameter of each document to the browser? I've tried replacing links with links.referer, but that sends undefined. Sometimes it throws an error saying that links has no 'referer' property. I've been stuck on this for a few hours now...

Upvotes: 1

Views: 1168

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

The second parameter to find lets you select which fields to include. Try replacing that line with:

Link.find {}, '-_id referer', (err, links) ->

_id must be explicitly excluded with the - prefix, but the rest of the fields are opt-in.

Upvotes: 3

Related Questions