读完 The Little MongoDB 书后,我今天才开始玩 mongoose。我对此很陌生,到目前为止,我已经知道如何从 mongoose 查询我的集合并根据它们的属性查找文档,但我想知道的实际上是如何为每个文档只显示文档的一个属性例如,在 Express res.send() 中的集合。就像一个学习实验,如果你愿意的话。
我在 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
这会将以下数据发送到用户的浏览器:
[
{
"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
}
]
我将如何仅将referer
每个文档的参数发送到浏览器?我试过用 替换links
,links.referer
但那会发送undefined
. 有时它会抛出一个错误,指出链接没有“引用者”属性。我已经坚持了几个小时了......