猫鼬返回数组中的一个嵌套文档

时间:2018-11-06 02:57:26

标签: javascript node.js mongodb mongoose nosql

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var userSchema = new Schema({
    _id:  Number,
    uname: String,
});

var postSchema = new Schema({
    _id:  Number,
    title: String,
    body: String
});

var threadSchema = new Schema({
    _id:  Number,
    tname: String,
    subs:  [ userSchema ],
    posts: [ postSchema ],
});

var threadModel = mongoose.model('threads',threadSchema);
var userModel = mongoose.model('users',userSchema);
var postModel = mongoose.model('posts',postSchema);

router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });

});

router.get('/thread/:threadname', function(req, res) {
    mongoose.connect('mongodb://localhost:27017/threads');

        threadModel.find( {tname : req.params.threadname} , function(err,thread){
            console.log(thread);
            res.render('thread', thread);
        })

});

router.get('/thread/:threadname/:postname', function(req, res) {
    mongoose.connect('mongodb://localhost:27017/threads');

    threadModel.find( {tname : req.params.threadname, posts: { _id:1 }}, 'posts' , function(err,post){
        console.log(post);
    })

});

module.exports = router;

在第二篇文章/ thread /:threadname /:postname中,我想查询一个嵌套文档并只得到一篇文章。相反,我将整个posts数组嵌套在数组文档中。

我也尝试过“ posts.title”:req.params.postname而不是posts:{_id:1}

如何根据帖子名称在线程对象内的帖子数组中找到单个帖子?

0 个答案:

没有答案