如何填充如果字段不是空字符串如果为空则不需要填充

How to populate if field is not empty string if empty no need to populate?

本文关键字:如果 填充 字符串 不需要 字段 何填充      更新时间:2023-09-26

我有一个应用程序,它以前在mongoDB中保存了大量数据。现在,如果referencePeople不是空字符串,我需要填充一些信息。在我的应用程序中,referencePeople是string类型,而不是mongoseObjectId的类型。

我不想更改我的模式。是否有任何方法可以在填充前检查referencePeople是否为空。或者如果为空,则避免填充。

架构:

var OrderSchema = new mongoose.Schema({
    customer: {type: mongoose.Schema.Types.ObjectId,ref: 'Customer'},
    referencePeople: String, // can be "" or "customer id"
   ......
});

尝试了以下代码,但出现异常对于路径"_id"处的值",强制转换到ObjectId失败

exports.getOrders = function(req, res) {
    Order.find({})
        .populate('customer')
        .populate({path: 'referencePeople', model: 'customer'})
        .exec(function(error, orders) {
            if(error) {
                return res.status(400).send({msg: 'Error occurred while getting orders.', error: error});
            }
            return res.status(200).send(orders);
        });
};

现在,如果不是空字符串,我想填充referencePeople。在填充referencePeople是否为空之前,我可以进行检查吗?

是的,您需要使用人口查询的match子句

所以,你的代码应该是这样的:

exports.getOrders = function(req, res) {
  Order.find({})
    .populate('customer')
    .populate({
       'path': 'referencePeople',
       'match': { 'referencePeople': {'$ne': ''} }
     })
    .exec(function(error, orders) {
        if(error) {
            return res.status(400).send({msg: 'Error occurred while getting orders.', error: error});
        }
        return res.status(200).send(orders);
    });

};

Mongoose还不能处理多级填充,填充的字段不是Documents。嵌套模式是有帮助的,但它是不完全解。相应地设计您的模式

您正试图使用2nd填充调用中的现有ObjectID引用"referencePeople"对象

试试这个

exports.getOrders = function(req, res) {
Order.find({})
    .populate('customer')
    .exec(function(error, orders) {
        if(error) {
            return res.status(400).send({msg: 'Error occurred while getting orders.', error: error});
        }
        //Try changing the referencePeople here
        return res.status(200).send(orders);
    });

};

参考:MongoDB

相关文章: