【发布时间】:2020-05-23 06:48:39
【问题描述】:
我正在尝试使用 MEVN 堆栈后端和 Vuex 构建 Vue.js 应用程序。我正在使用 GET 请求配置我的 Vuex 操作处理程序,该请求会提示相应的 Express GET 路由以查询嵌套在 Mongoose 中的数据。
用户名作为参数传递给处理程序,并作为参数附加到 GET 请求 URL:
actions: {
loadPosts: async (context, username) => {
console.log(username)
let uri = `http://localhost:4000/posts/currentuser?username=${username}`;
const response = await axios.get(uri)
context.commit('setPosts', response.data)
}
}
对应的Express路由查询activeUser.name,表示Mongoose模型中的嵌套数据:
postRoutes.route('/currentuser').get(function (req, res) {
let params = {},
username = req.query.activeUser.name
if (username) {
params.username = username
}
Post.find(params, function(err, posts){
if(err){
res.json(err);
}
else {
res.json(posts);
}
});
});
下面是我的Mongoose模型,activeUser.name代表Express路由查询的嵌套数据:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Post = new Schema({
title: {
type: String
},
body: {
type: String,
},
activeUser: {
name: {
type: String
}
}
},{
collection: 'posts'
});
module.exports = mongoose.model('Post', Post);
即使使用此设置,GET 路由似乎也不会将响应发送回操作处理程序。我认为在快速路由中添加username = req.query.activeUser.name 是在 Mongoose 中查询嵌套数据的正确方法,但显然不是。关于如何配置上述 Express 路由以查询 Mongoose 模型中的嵌套数据的任何建议?谢谢!
【问题讨论】:
-
输出是什么
posts -
Manjeet Thakur,你能澄清一下你在问什么吗?
-
Post.find(params, function(err, posts){ console.log(err, posts)}
-
我在那里尝试了 console.log,但没有输出。服务器返回错误:
Cannot read property 'name' of undefined -
将 req.query.activeUser.name 更改为 req.query.activeUser.username
标签: mongodb express vue.js mongoose vuex