如何在保存之前检查数据库中是否已存在该数据

时间:2017-05-12 09:59:37

标签: node.js mongodb express mongoose

嘿伙计们我有一个问题,如何在用mongoose保存编辑或发布(发布或放置操作)数据之前进行验证??

例如,如果数据库中已存在操作,则用户将收到某种错误。我尝试这个但不工作: 1-NOT WORK

>>> if the_world_is_flat:
...   print("Be careful not to fall off!")
... 
Be careful not to fall off!
>>> print (text)
# but this is not since quotes

2 ---不工作第二种方法:------------------------------------

var mongoose = require("mongoose"),
    Schema = mongoose.Schema;

var actionSchema = new Schema({
    action: {
          type: String,
          required: true,

            },
    });

var data = mongoose.model('Action', actionSchema);

actionSchema.pre('save', function (next) { // Middlware to verify if action already existe
   var self = this;
   data.find({
     action: self.action
   }, function (err, actions) {
     if (!actions.length) {
         next();
      } else {
          console.log('action exists: ', self.name);
          next(new Error("Action exists!"));
      }
   });
});

module.exports = mongoose.model('Action', actionSchema);

3-工作替代 - NODE JS控制器----我发现这个技巧(工作正常)是在更新之前进行检查(检查) 但我想知道是否有可能在我保存模型MONGOOSE之前做到这一点!?

 var data = mongoose.model('Action', actionSchema);

actionSchema.pre('save', function (next) {
data.count({
    action: this.action
}, function (err, count) {
    if (count == 1) {
        console.log('action exists: ', this.action);
        next(new Error("Action exists!"));
        //already exists
      } else {
          next();
          //do the action 
      }
   });
  });

2 个答案:

答案 0 :(得分:0)

检查数据是否已经可用,然后执行您想要的操作

 var data = mongoose.model('data', actionSchema);
 data.count({action: this.action}, function(err, count) {
   if(count == 1){
     //already exists
    }
      else{
   actionSchema.pre('save', function (next) {
       });
         }
      });

答案 1 :(得分:0)

我不明白你为什么要做太多操作才能做一次操作。 Mongodb提供了具有检查和插入功能的更新功能。如果您希望仅在某些条件成立或出现错误时插入文档。 update可以在单个查询中执行此操作。你走了。

Action.update({ action:{ $eq:req.body.action }},{ $setOnInsert: new_action }, { upsert: true }, function(err, res){
    if(!err && !!res.upserted){
        // no document was found hence inserted
    }else if(!err && !res.upserted){
        // already existing
    }else{
        //  something wicked happend
    }
})

在这里,您需要注意new_action不能是您的猫鼬模型的实例,而应该是您要插入的简单对象/文档。

相关问题