【问题标题】:checking of field in a document检查文档中的字段
【发布时间】:2014-07-25 09:29:16
【问题描述】:

假设我有以下架构

 var userSchema = new Schema({
    name : String
  });

  var User = mongoose.model('User',userSchema);

编辑:如果用户尝试更新不存在的字段,我需要抛出异常。我的问题是如何检查更新文档中不存在更新字段。这是我需要的一个小例子:

  app.post('/user/update/:id', function (req, res) {
     var field = req.param('field'),
          value = req.param('value'),
          id = req.param('id');

     User.findOne({_id: id},function(err, user){
        if(err) throw err;

        if (user) {

          user[field] = value;          // Here is I need to check that field is exists
                                        // in user schema. If does't I have to throw 
                                        // an execption.

          user.save(function (err){
             return res.send(200);
          });
        }            
     })
  });

【问题讨论】:

  • 我不清楚你的问题是什么
  • 因为他没有问问题,他只是陈述了他的所作所为
  • 我添加了有关我的问题的更多信息

标签: node.js mongodb express mongoose


【解决方案1】:

尝试将$exists 添加到update() 的查询参数中。这将允许您仅在某个字段存在(或不存在)时更新文档。

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24exists

【讨论】:

  • 谢谢你的回复,但如果没有扩展,我需要一个扩展。
  • @Erik - 对,如果它不存在,那么您可以使用$exists 检查更新结果以查看 nupdated = 0(如果您使用的是安全模式),并且然后在那里抛出异常。
【解决方案2】:

来自 Mongoose v3.1.2 指南:

strict 选项(默认启用)确保添加到模型实例中但未在我们的架构中指定的值不会保存到数据库中。注意:除非你有充分的理由,否则不要设置为 false。

strict 选项也可以设置为“throw”,这将导致产生错误而不是忽略坏数据。

http://mongoosejs.com/docs/guide.html#strict

【讨论】:

    【解决方案3】:
    var CollectionSchema = new Schema({name: 'string'}, {strict: 'throw'});
    
    Collection.findById(id)
      .exec(function (err, doc) {
        if (err) {// handle error};
    
        // Try to update not existing field
        doc['im not exists'] = 'some';
        doc.save(function (err) {
          if (err) {
             // There is no an errors
          }
    
          return res.json(200, 'OK');
        });
    
      });
    

    在上面的示例中,当我更新一个不存在的字段时,我没有收到错误。

    【讨论】:

      【解决方案4】:

      您可以使用.schema.path() 来检查field 是否存在于schema 中。在您的特定用例中,您可以执行以下操作:

      app.post('/user/update/:id', function (req, res) {
       var field = req.param('field'),
            value = req.param('value'),
            id = req.param('id');
      
        User.findOne({_id: id},function(err, user){
          if(err) throw err;
      
          if (user) {
      
            if(User.schema.path(field)) {
              user[field] = value;
            } else {
              throw new Error('Field [' + field + '] does not exists.');
            }
      
            user.save(function (err){
              return res.send(200);
            });
          }            
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2019-03-04
        • 2021-10-26
        • 2018-08-28
        • 2023-03-07
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2022-07-13
        • 1970-01-01
        相关资源
        最近更新 更多