首页 > 解决方案 > 从查找 mongodb 中一无所获

问题描述

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

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);

//用户模型

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);

//节点js

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));
    }
});    
});

//输出

 {"_id":"5b9c7f30d",
 "author": {"uid":"y08RxtsHe","name":"Sujoy Saha"},
 "tags": ["#lo"],
 "likes":[],  "comments[],

 "category":"image","content":"jsdnvs","caption":"standing 
 \n#lol","createdAt":1536982759517,"__v":0,"creator":[]}

你可以看到,我得到了空的创建者数组。请帮帮我。

标签: node.jsmongodb

解决方案


mongoose.js 在 MongoDb 中创建集合时会进行复数化(在模型名称后添加“s”)。

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


推荐阅读