node.js - 从查找 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":[]}
你可以看到,我得到了空的创建者数组。请帮帮我。
解决方案
mongoose.js 在 MongoDb 中创建集合时会进行复数化(在模型名称后添加“s”)。
from: 'users'
您可以在 $lookup 子句中尝试使用吗?
推荐阅读
- python - 索引 numpy 数组,每列有两个数组,开始和结束
- python-3.x - 在 Python 中使用 Excel 命令
- typescript - Jest/Mocha + TypeScript:Jest/Mocha 尝试读取 JS 依赖项并失败 - “意外的令牌导入”
- node.js - 在特定时间删除 Mongoose,Nodejs 用户
- reactjs - 部署后如何更改 ReactJS 中的变量
- java - JavaFX 8 + Spring Boot,打印 API 不显示页面设置
- php - Cakephp 迁移 - 一般错误:1215 无法添加外键约束
- c# - 隐藏/显示列(ObjectListView)?
- git - 将所有本地引用和分支推送到 git 上游
- python - 线程条件获取锁实际上并没有获取锁