gpt4 book ai didi

javascript - 如何使用 mongoose 对 Nodejs 中填充结果的子文档数组进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:45 25 4
gpt4 key购买 nike

我想根据时间检索成员(member)最近提交的文章。成员架构具有已提交文章的 _id 数组。以下是成员和文章的架构 -

成员架构

    const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MemberSchema = new Schema({
uid:{
type:String,
required:[true,'Must Required']
},
name:{
type:String,
default:[true,'Anonymous']
},
email:{
type:String,
required:[true,'Email Must Required']
},

profileimg:{
type:String ,
required:[true,'Profile Image Must Required']
},
notes:{
type:String,
default:[true,'Write your Notes Here']
},
country:{
type:String,
default:[true,'America']
},
profession:{
type:String,
default:[true,'Developer']
},
experience:{
type:String,
default:[true,'5']
},
article:[{_id:{type : mongoose.Schema.Types.ObjectId,ref : 'Article'}}]



});

const Member = mongoose.model('member',MemberSchema);

module.exports = Member;

文章架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ContentCardSchema = new Schema({
cardtitle : String,
cardbody : {
type:String
}
});
const ArticleSchema = new Schema({
_id:mongoose.Schema.Types.ObjectId,
author:{
type: mongoose.Schema.Types.ObjectId, ref: 'member' ,
required:[true,'UID Must Required']
},
status:{
type:String,
default:'PENDING'
},
category:{
type:String,
default:'Other'
},
title:{
type:String,
default:'Anonymous'
},
body:[ContentCardSchema],
thumbimg:{
type:String,
required:[true,'Thumb Image Must Required']
},
date: {
type: Date,
default:Date.now
}



});

const Article = mongoose.model('Article',ArticleSchema);

module.exports = Article;

时间存储在文章架构中,而不是存储在成员架构数组中。我想首先获得最近文章中的输出。

下面是 Mongoose 填充操作,具有排序功能,但不起作用。

//Get Article Submitted by their Author using uid
router.get('/author/:uid',(req,res,next)=>{
Member.findOne({uid:req.params.uid},'article').populate('article._id','title category thumbimg')
.exec()
.then((result)=>{
res.status(200).json(result);
})
.catch(err=>{
res.send(404).json({error:err});
})
});

最佳答案

//Get Article Submitted by their Author using uid
router.get('/author/:uid',(req,res,next)=>{
Member.findOne({uid:req.params.uid},'article')
.populate({path:'article._id',select: 'title category thumbimg', options: {sort : {yourfieldname :1}})
.exec()
.then((result)=>{
res.status(200).json(result);
})
.catch(err=>{
res.send(404).json({error:err});
})
});

尝试上面的方法。希望这会有所帮助。

关于javascript - 如何使用 mongoose 对 Nodejs 中填充结果的子文档数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50627403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com