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

let obj ={name:"joasn"};

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

阅读 4.4k
2 个回答

確實是使用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));
});

这个看看文档就知道了啊。update可以配置option upsert 用来在没有匹配时候直接插入

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题