【问题标题】:getting nothing from lookup mongodb从查找 mongodb 中一无所获
【发布时间】:2019-02-20 22:51:25
【问题描述】:

我想从用户模型中获取所有带有作者详细信息的帖子。我正在使用 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.js mongodb


    【解决方案1】:

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

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

    【讨论】:

    • 试过了。结果相同。
    • @Sujoy 你确定你使用的是users,而不是Users?因为它区分大小写。
    • 我已将其更改为“用户”,现在它可以工作了。现在我的问题是为什么它是“用户”,尽管我在代码的其他部分使用了“用户”?
    • @Sujoy 很高兴听到您的代码正在运行。这是因为,在 $lookup 子句中,您需要指定集合的​​名称而不是 mongoose 模型名称。默认情况下,当您在 mongoose 中定义模型时,mongoose 会创建一个具有复数和小写名称的集合。仅供参考,mongoDB 集合名称区分大小写,但建议使用小写名称。
    猜你喜欢
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    相关资源
    最近更新 更多