node.js - mongoose save时,如果数据库不存在同样的数据才执行

查看:64
本文介绍了node.js - mongoose save时,如果数据库不存在同样的数据才执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

let obj ={name:"joasn"};

如果数据库里不存name为joasn的时候,才向数据库中插入,请问该怎么实现呢?

解决方案

確實是使用Collection.update

update(selector, document, options, callback)
Updates documents.

Name Type Degault Description
selector object The selector for the update operation.
document object The update document.
options object null [optional] Optional settings.
callback Collection~writeOpCallback [optional] The command result callback

options中有一個upsert屬性(Type: boolean),用於確定這是否是一個 upsert 操作。即但不存在selectop匹配的文檔時,是否插入文檔


name相同則更新,不同則插入:

代碼應該是這樣的:

var urDocument = { // 你想插入的文檔
  name: "joasn",
 other: "ohaedoaduantoduntaodutaod"
};

var MongoClient = require('mongodb').MongoClient,
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  var collection = db.collection('collocation');

  collection.update({name: {$ne: urDocument.name}, {upsert: true}, urDocument);

});

name相同則不作為,不同則插入:

var UrDocument = { // 你想插入的文檔
  name: "joasn",
 other: "ohaedoaduantoduntaodutaod"
};

var MongoClient = require('mongodb').MongoClient,
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

  var collection = db.collection('collocation');

  collection.findOne({name: urDocument.name })
      .then(doc => doc ?? collection.insertOne(urDocument));
});

这篇关于node.js - mongoose save时,如果数据库不存在同样的数据才执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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