简体   繁体   English

检查 mongoose sava() data 如果不存在则创建文档,否则更新数据

[英]checked mongoose sava() data Create document if not exists, otherwise, update data

i have mongoose schema save ever 1 sec if data is already exists update that document如果数据已经存在,我有猫鼬模式保存 1 秒更新该文档

   this.sub.on('message',async function (topic, message) {
        const soilesensor = new SensorModel({
            topic: topic,
            value : parseFloat(message.toString())
          })
          await soilesensor.save();
          cb && cb(topic,message); 
    })

my mongoose schema is我的猫鼬模式是

const mongoose = require('mongoose')


const sensor = mongoose.Schema({
    topic : {type : String ,index : true},
    value : {type :Number ,index : true},
    date: { type: Date, default: Date.now ,  index: true}
})

const Sensor = mongoose.model('Sensors' , sensor )

module.exports = Sensor ;

i just save document if data is already exists update that document如果数据已经存在,我只保存文档更新该文档

You can use upsert .您可以使用upsert You need to pass upsert: true你需要通过upsert: true

Try below example:试试下面的例子:

db.books.update(
   { item: "ZZZ135" },   // Query parameter
   {                     // Replacement document
     item: "ZZZ135",
     stock: 5,
     tags: [ "database" ]
   },
   { upsert: true }      // Options
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查文档是否已经存在,如果是,则进行更新,否则创建新的-猫鼬 - Check if document already exists and if yes then update, otherwise create new - Mongoose Mongoose - 如果不存在则创建文档,否则,更新 - 在任何一种情况下都返回文档 - Mongoose - Create document if not exists, otherwise, update- return document in either case 如果存在则更新 Many ,否则为每个不存在的 LeadId 创建一个新文档 - Update Many if exists , otherwise create for each LeadId that doesn't exists a new Document Sava数据到可变位置[Firebase] - Sava Data to a variable Place [Firebase] 如何更新mongoose中的子文档数据? - How to update the child document data in mongoose? 从引导Javascript模式到数据库的Sava数据 - Sava data from bootstrap javascript modal to database 如何仅使用选中的复选框数据更新 mongodb 文档 - How to update mongodb document with only checked checkbox data 如何从Ext.Store到数组的sava数据? - How to sava data from Ext.Store to array? 如果值存在则应用过滤器,否则忽略-猫鼬 - Apply filter if value exists otherwise ignore - mongoose 如果localStorage中存在数据,如何将其返回,否则执行AJAX请求? - if data exists in localStorage, how to return it, or otherwise perform AJAX request?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM