我对Node.js和MongoDB非常陌生,正在尝试拼凑我自己的博客应用程序。我在尝试通过我的“博客”模型查询具有特定用户名的博客时遇到了问题。当我尝试运行时:
var userBlogs = function(username) {
ub = Blog.find({author: username}).toArray();
ub = ub.reverse();
};我得到一个错误:
TypeError: Object #<Query> has no method 'toArray'我知道全局变量是不好的,但我只是想让它正常工作。Mongo文档声称返回了一个游标,可以在其上调用toArray()方法。我不知道为什么它不能工作。
下面是我创建的模式/模型:
var blogSchema = mongoose.Schema({
title: {type:String, required: true},
author: String,
content: {type:String, required: true},
timestamp: String
});
var Blog = mongoose.model('Blog', blogSchema);下面是/login和/readblog请求
app.get('/readblog', ensureAuthenticated, function(req, res) {
res.render('readblog', {user: req.user, blogs: ub})
})
app.get('/login', function(req, res){
res.render('login', { user: req.user, message: req.session.messages });
});
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login'}),
function(req, res) {
userBlogs(req.user.username);
res.redirect('/');
});
});最终结果应该与这个Jade一起工作:
extends layout
block content
if blogs
for blog in blogs
h2= blog[title]
h4= blog[author]
p= blog[content]
h4= blog[timestamp]
a(href="/writeblog") Write a new blog如何让查询输出数组,甚至作为对象工作?
发布于 2013-12-31 23:26:12
toArray函数存在于本机MongoDB NodeJS驱动程序(reference)的Cursor类上。MongooseJS中的find方法返回一个Query对象(reference)。有几种方法可以进行搜索并返回结果。
由于MongoDB的NodeJS驱动程序中没有同步调用,因此在所有情况下都需要使用异步模式。MongoDB的示例通常在使用MongoDB控制台的JavaScript中,这意味着本机驱动程序也支持类似的功能,但它不支持类似的功能。
var userBlogs = function(username, callback) {
Blog.find().where("author", username).
exec(function(err, blogs) {
// docs contains an array of MongooseJS Documents
// so you can return that...
// reverse does an in-place modification, so there's no reason
// to assign to something else ...
blogs.reverse();
callback(err, blogs);
});
};然后,将其称为:
userBlogs(req.user.username, function(err, blogs) {
if (err) {
/* panic! there was an error fetching the list of blogs */
return;
}
// do something with the blogs here ...
res.redirect('/');
});您还可以对字段进行排序(例如,博客发布日期):
Blog.find().where("author", username).
sort("-postDate").exec(/* your callback function */);上面的代码将根据一个名为postDate (替代语法:sort({ postDate: -1}) )的字段按降序排序。
发布于 2014-12-02 05:13:07
试着做一些类似的事情:
Blog.find({}).lean().exec(function (err, blogs) {
// ... do something awesome...
} 发布于 2013-12-31 22:06:59
你应该利用find的回调:
var userBlogs = function(username, next) {
Blog.find({author: username}, function(err, blogs) {
if (err) {
...
} else {
next(blogs)
}
})
}现在你可以调用这个函数来获取你的博客了:
userBlogs(username, function(blogs) {
...
})https://stackoverflow.com/questions/20858299
复制相似问题