避免在没有数据的情况下插入 mongoDB [英] Avoid insertion in mongoDB Without Data

查看:55
本文介绍了避免在没有数据的情况下插入 mongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果没有数据,如何避免在 mongoDB 中插入.因为每次我使用插入命令时,它都会创建没有数据的 _id.示例:db.collection_name.insert({})正在文档中创建 _id.如何避免.

How can i avoid the insertion in mongoDB if there is no data. Because every time i use insert command it is creating _id without data. Example : db.collection_name.insert({}) is creating _id in document. How to avoid it.

推荐答案

MongoDB 3.2 集成了模式验证.所以你可以只检查name"属性是否存在,如果不存在则验证失败,然后根本不会插入文档.

MongoDB 3.2 has schema validation integrated. So you can just check if "name" property exists, if not then the validation fail and then the Document will be not inserted at all.

https://docs.mongodb.com/v3.2/核心/文档验证/

db.createCollection( "contacts",
   { validator: { $or:
      [
         { phone: { $type: "string" } },
         { email: { $regex: /@mongodb\.com$/ } },
         { status: { $in: [ "Unknown", "Incomplete" ] } }
      ]
   }
} )

这篇关于避免在没有数据的情况下插入 mongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆