从查找mongodb中什么也没得到

时间:2018-09-17 03:52:12

标签: node.js mongodb

我想从用户模型中获取所有帖子及其作者详细信息。我正在使用mongoDB查找。但是得到一个空数组。我从发帖到用户的_id匹配author.uid。 我想从用户模型中获取所有帖子及其作者详细信息。我正在使用mongoDB查找。但是得到一个空数组。我从发帖到用户的_id匹配author.uid。 //发布模型

encodeURIComponent

//用户模型

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const postSchema = new Schema({
category : {
    type: String
},
content: {
    type: String
},
caption: {
    type: String
},
tags: [{
    type: String
}],
createdAt: {
    type: Number,
    required: true
},
 author: {
    uid:{
        type: String,
        required: true
    },
    name:{
        type: String
    }
},
likes:[{
    type:String
}],

comments:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: "Comment"
}]

});

module.exports = mongoose.model('Post', postSchema);

//节点js

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
_id: {
    type: String,
    required: true
},
name:{
    type: String,
    required: true
},
avatar:{
    type:String
},
bio:{
    type: String
},
followers:[
    {
        type: String 
    }
],
followings:[
    {
        type: String
    }
],
posts:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: "Post"
}]
});

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

//输出

const express = require('express');
const router = express.Router();

const Post = require('../../models/Post');
const User = require('../../models/user');

router.get('/', (req, res) => {
Post.aggregate([
    {
        $lookup:
            {
                from: 'User',
                localField: "author.uid",
                foreignField: "_id",
                as: "creator"
            }
    }
]).exec((err, result) => {
    if (err) {
        console.log("error" ,err)
    }
    if (result) {
        console.log(JSON.stringify(result));
    }
});    
});

您可以看到,我正在获得空的创建者数组。请帮帮我。

1 个答案:

答案 0 :(得分:0)

mongoose.js在MongoDb中创建集合时将复数形式(在模型名称后添加's')。

您可以在$ lookup子句中尝试使用from: 'users'吗?