【问题标题】:Mongoose query in an Object对象中的猫鼬查询
【发布时间】:2019-02-24 03:49:30
【问题描述】:

问题,我得到了一个使用 mongoose 的架构,它创建了一个对象。我不知道如何查询author id,它将返回author Id下的对象列表

var mongoose = require("mongoose");
var bookedSchema = new mongoose.Schema({
   origin: String,
   destination: String,
   author: { id: { type: mongoose.Schema.Types.ObjectId, ref: "User"}, username: String},
   Date: {type: Date, default: Date.now}
});
module.exports = mongoose.model("Booked", bookedSchema);

在我的路线上,我有查询 find({}) 我想查询作者 ID 而不是 {},它将返回作者 ID 下的对象列表。我尝试了findById(author:{id:req.user._id}),但它返回了空答案。任何想法如何做到这一点。谢谢!

router.get('/myAccount', function(req, res){
    Booked.find({}).exec(function(err, booked){
        if(err){
            console.log(err);
            // res.redirect('back');
        }else{
            console.log(booked)
            res.render('accounts/myAccount', {booking:booked});
        }
    });
});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您应该对引用的文档使用 .populate() 来填充它们。 改变这个:

    Booked.find({}).exec(function(err, booked)
    

    到:

    Booked.find({}).populate('author').exec(function(err, booked)
    

    或者如果您需要通过引用的作者 ID 查找文档,您可以使用:

    Booked.find({}).populate({
      path: 'author',
      match: { id: { $eq: req.user._id }}
    }).exec(function(err, booked)
    
    

    【讨论】:

    • 嗨 Arootin,感谢您的回复,我使用了 populate("author"),但我收到错误`Cast to ObjectId failed for value "admin" at path "_id" for model Booked`
    • 无论如何,另一种情况是可以查询像Booked.find({}).exec(function(err, booked)这样的对象我想解析booked.origin?我尝试了console.log(booked.origin),但它给出了undefined
    • 我认为这会解决这个问题:path: 'author.id'
    猜你喜欢
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 2014-04-21
    • 2012-01-09
    相关资源
    最近更新 更多