在阅读The Little MongoDB书之后,我今天刚开始玩猫鼬。我对此很陌生,到目前为止我已经知道如何从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
。有时它会抛出错误,说链接没有'referer'属性。我已经被困在这几个小时了......
答案 0 :(得分:3)
find
的第二个参数可让您选择要包含的字段。尝试用以下代码替换该行:
Link.find {}, '-_id referer', (err, links) ->
必须使用_id
前缀明确排除 -
,但其余字段均为选择加入。