【问题标题】:How to query nested data in mongoose model如何在猫鼬模型中查询嵌套数据
【发布时间】: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


【解决方案1】:

nameactiveuser 内部,所以你需要像这样构造 params 对象变量:

postRoutes.route("/currentuser").get(function(req, res) {
  let params = {
    activeUser: {}
  };

  let username = req.query.activeUserName;

  if (username) {
    params.activeUser.name = username;
  }

  Post.find(params, function(err, posts) {
    if (err) {
      res.json(err);
    } else {
      res.json(posts);
    }
  });
});

请注意,我还使用 activeUserName 作为查询参数,如下所示:/currentuser?activeUserName=JS_is_awesome18

【讨论】:

  • 您的回答也极大地提高了我对 Express 路由中查询工作原理的理解。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 2018-06-23
  • 2019-04-05
  • 2013-07-21
  • 2021-12-25
相关资源
最近更新 更多