如何搜索猫鼬模式对象?

问题描述 投票:0回答:2

[我试图搜索所有注释并从mongodb返回特定用户创建的所有注释,但是当我尝试搜索返回的数组时,它是空的。

我已经尝试过:

Comment.find({author: {$elemMatch: {username: req.params.username}}}, (err, foundComments) => {
        // Code goes here
      });

猫鼬评论模式:

const mongoose = require('mongoose');

const commentSchema = new mongoose.Schema({
  text: String,
  discussion:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Comment',
  }],
  createdAt: {
    type: Date,
    default: Date.now,
  },
  author: {
    id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
    },
    username: 'String',
    avatar: {
      image: String,
      imageId: String,
    },
  },
  likes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  }],
  dislikes: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  }],
});

module.exports = mongoose.model('Comment', commentSchema);

[运行时,我期望foundComments是数组[ array of comments ],但我只得到一个空数组[]

node.js mongodb mongoose
2个回答
0
投票
Comment.find({"username": req.params.username},{"discussion":1,"_id":0})

0
投票

Comment.find({"author.username":req.params.username});

© www.soinside.com 2019 - 2024. All rights reserved.