node.js - mongoose save时,如果数据库不存在同样的数据才执行
本文介绍了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屋!
查看全文