关联字段ObjectId上的过滤器集合

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

我有一个使用MongoDB和Mongoose并带有文章和评论集合的Node.js Express Web应用程序。他们有一对多关联,其中一篇文章可以有很多评论。猫鼬模型架构如下:

// models/article
const mongoose = require('mongoose');
const articleSchema = new mongoose.Schema({
  title: { type: String },
  content: { type: String },
}, {timestamps: true});
module.exports = mongoose.model('Article', articleSchema);

// models/comment.js
const mongoose = require('mongoose');
const commentSchema = new mongoose.Schema({
  content: { type: String },
  article: { type: mongoose.Schema.Types.ObjectId, ref: 'Article' },
}, {timestamps: true});
module.exports = mongoose.model('Comment', commentSchema);

我有一条带有商品ID参数的路线

// routes.js
router.get('/articles/:articleId/comments', commentsController.list);

以及具有回调功能的控制器,用于查询数据库并返回具有给定商品ID的注释。它使用mongoose find()方法对从route参数获取的商品ID进行过滤。

// controllers/commentsController.js
exports.list = (req, res, next) => {
  Comment.find({ article: req.params.articleId })
  .exec((err, comments) => {
    res.render('comments/list', { title: 'Comments', comments: comments });
  });
};

但是这没有结果。只是做实验,我可以看到req.params.articleId是一个字符串,任何comment.article是一个对象,因此它们匹配的是松散的比较==,但不是严格的比较===,除非我转换comment.article.toString() 。无论如何,执行这种查询的正确方法是什么。我所有的尝试都失败了。

node.js mongodb express mongoose associations
1个回答
0
投票
Comment.find({ article: mongoose.Types.ObjectId(req.params.articleId) })
© www.soinside.com 2019 - 2024. All rights reserved.