如何使用mongoose查询数组以查找子文档?

时间:2017-11-22 18:38:39

标签: node.js mongodb mongoose

我希望查询包含数组的子文档。

您可以将此视为类似于medium.com或tumblr.com的应用程序:

我有一个用户架构,而且用户有很多帖子。我的帖子架构有一个'标签' key是一个数组我试图创建一个路径,显示所有具有特定标签的帖子。

例如,

GET /user/posts/:tag
GET /user/posts/dogs

可能会返回包含标记“狗”的所有帖子(由任何用户)的数据

{
  description: 'dogs are cool',
  title: 'huskies',
  tags: ['dogs','animals','outdoors'],
  original_poster: '34255352426'
},{
  description: 'My puppies are nice',
  title: 'Puppies',
  tags: ['pugs','dogs','small'],
  original_poster: '44388342426'
},{
  description: 'I like cats more than dogs',
  title: 'Cats',
  tags: ['kittens','cats','dogs'],
  original_poster: '15708213454'
} 

这是我的用户架构:

const mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    PostSchema = require('./post-model.js');

let UserSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: false, //only required for local users
        unique: false,
        default: null
    },
    following: {
        type: [Number], 
        required: false,
        unique: false
    },
    followers: {
        type: [Number],
        required: false,
        unique: false
    },
    posts: [PostSchema],
})

module.exports = mongoose.model('User',UserSchema);

这是我的帖子架构:

const mongoose = require('mongoose'),
    Schema = mongoose.Schema;

let PostSchema = new Schema({
    description: {
        type: String,
        required: false,
        unique: false
    },
    title: {
        type: String,
        required: false,
        unique: false
    },
    tags: {
        type: [String],
        required: true
    },
    original_poster: { 
      type: String,
      required: true
    }
});

module.exports = PostSchema;

编辑:

澄清我的问题,想象一下这是一个常规的js对象,这里是一个返回与特定标签相关的所有数据的函数:

let users = [];
let user1 = {
  username: 'bob',
  posts: [
    {
      title: 'dogs r cool',
      tags: ['cats','dogs']
    },
    {
      title: 'twd is cool',
      tags: ['amc','twd']
    }]
};
let user2 = {
  username: 'joe',
  posts: [{
    title: 'mongodb is a database system that can be used with node.js',
    tags: ['programming','code']
  },
  {
    title: 'twd is a nice show',
    tags: ['zombies','horror-tv','amc']
  },
    {
      title: 'huskies are my favorite dogs',
      tags: ['huskies','dogs']
    }]
}

users.push(user1);
users.push(user2);

function returnPostByTag(tag) {
  let returnedPosts = [];

  users.forEach((user,i) => {
    user.posts.forEach((post) => {
      if(post.tags.includes(tag)) {
        let includespost = {}
        includespost.title = post.title;
        includespost.tags = post.tags;
        includespost.original_poster = user.username;
        returnedPosts.push(includespost);
      }
    })
  })
  return returnedPosts;
}

如果你想查看一个完整的repl,我在这里使用一个简单的js示例:https://repl.it/repls/LavenderHugeFireant

1 个答案:

答案 0 :(得分:0)

您可以使用Mongoose执行以下操作,以返回posts数组中任何子文档中的tags数组包含标记的所有用户:

User.find({ 'posts.tags': tag }, function(err, users) {
  if (err) {
    // Handle error
  }

  let filteredPosts = users
    .map(user => {
      user.posts.forEach(post => post.original_poster = user.username)
      return user
    })
    .map(user => user.posts)
    .reduce((acc, cur) => acc.concat(cur), [])
    .filter(post => post.tags.includes(tag))

  // Do something with filteredPosts
  // ...such as sending in your route response
})

... 用户是您的Mongoose模型,标记包含您要查询的标记字符串(可能来自您的路径请求)。

如果您使用的是承诺,那么您可以这样做:

User.find({ 'posts.tags': tag })
  .then(users => {

    let filteredPosts = users
      .map(user => {
        user.posts.forEach(post => post.original_poster = user.username)
        return user
      })
      .map(user => user.posts)
      .reduce((acc, cur) => acc.concat(cur), [])
      .filter(post => post.tags.includes(tag))

    // Do something with filteredPosts
    // ...such as sending in your route response

  })
  .catch(err => {
    // Handle error
  })