javascript - 如果字段不为空字符串如何填充如果为空则不需要填充?

标签 javascript angularjs node.js mongodb

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

我不想更改我的架构。有什么方法可以在填充之前检查 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之前检查是否为空吗?

最佳答案

是的,您需要使用population queryma​​tch子句

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

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);
    });

};

关于javascript - 如果字段不为空字符串如何填充如果为空则不需要填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33870204/

相关文章:

javascript - AngularJs:默认情况下未选择单选按钮

angularjs - 没有 ng-repeat 的 Angular 中的替代样式 <ul> 元素

node.js - 从 ECS 集群中的 docker nodejs EC2 容器连接到 Redis Elasticache 集群

javascript - 在不编辑 html 的情况下相对于另一个 css 元素定位一个元素

javascript - 在 javascript 中更改边框颜色的问题

javascript - 如何从 $mdDialog 中的 URL 打开页面?

javascript - 解析 js - 无法接收用户字段

javascript - 使用socket.io发送鼠标点击事件

javascript - 元素在调整大小时不断离开 Div

javascript - 如何在使用 Javascript 提交之前调整 Django Imagefield 中的图像大小