提问者:小点点

在通过参数传递objectId时,无法从MongoDB获取所有文档详细信息


我只获取文档中存在的对象。。。

这是路线的代码行

router.get('/product-by-id/:ProductId', async (req,res) => {
    const {ProductId} = req.params; 
    const Id= await Prod.findById({_id:ProductId})
    return res.send(Id);
})
const mongoose= require('mongoose'); 
const Schema= mongoose.Schema;

const productSchema = mongoose.Schema({
    
    author: {
        type: Schema.Types.ObjectId,
        ref:  'users'
    },
    title: {
        type:String,
        maxlength: 50 
    },
    description:{
        type: String
    }, 
    file: {
        data: Buffer,
        contentType: String 
    }, 
    duration:{
        type:String
        
    }, 
    cat: {
        type:String,
        enum:["Shoes","Appliances","Apparel","Accessories","Electronics","Books","PC Parts"]
    },
    
    barter:{
        type: String
    }
}, {timestamp: true })

const Prod = mongoose.model('Prod', productSchema);

module.exports= Prod

我在邮递员上测试了路由,但只得到了文件对象,而没有其他。。。非常感谢您的帮助。


共2个答案

匿名用户

您的方法看起来不错,只是在使用findbyId直接传递ID时需要一个小的修正。 像这样

let ProductId = req.params.ProductId
const Id= await Prod.findById(ProductId) 

匿名用户

首先,当您使用findById()时,您只需要实际的ID,您可以这样做:

let productId = req.params.ProductId

然后,您需要通过执行以下操作之一来触发查询的执行:

a.使用.exec()

   const Id= await Prod.findById(productId).exec()
   return res.send(Id)

b.使用回调方法

await Prod.findById(productId ,(err, result)=>{
        return res.send(result)
    })
  

c.调用.then()

 await Prod.findById(productId).then((err, result)=>{
   if(!err){
    return res.send(result)
   }
 })