How to query nested data in mongoose model

北城余情 提交于 2020-02-25 04:11:06

问题


I am attempting to build a Vue.js app with a MEVN stack backend and Vuex. I am configuring my Vuex action handler with a GET request that prompts a corresponding Express GET route to query data nested in Mongoose.

A username is passed into the handler as an argument and appended to the GET request URL as a parameter:

  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)
    }
  }

The corresponding Express route queries activeUser.name, which represents the nested data in the Mongoose Model:

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);
    }
  });
});

Below is my Mongoose model, with activeUser.name representing the nested data queried by the Express route:

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);

Even with this setup, the GET route does not appear to send a response back to the action handler. I thought adding username = req.query.activeUser.name in the express route would be the right method for querying the nested data in Mongoose, but apparently not. Any recommendations on how to configure the above Express route in order to query the nested data in the Mongoose model? Thanks!


回答1:


name is inside activeuser so you need to construct params object variable like this:

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);
    }
  });
});

Note that I also used activeUserName as query param like this: /currentuser?activeUserName=JS_is_awesome18



来源:https://stackoverflow.com/questions/60108257/how-to-query-nested-data-in-mongoose-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!