ここにサンプルコードです。 MongoDBデータベースの値の存在は、OPで述べたようにreq.body
に依存することに注意してください。
以下のコードでは、Student
コレクションには名前属性しかありません。したがって、重複チェックはname属性のみに基づいています。
コレクション内の特定の属性をチェックして重複値を確認する場合は、コードを変更する必要があります。
私のStudent
コレクションには、スキーマ内の属性だけがあることに注意してください。
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Student = mongoose.model('Student', { name: String });
var app = express();
var bodyParser = require('body-parser');
var app = express();
var urlencoded_body_parser = bodyParser.urlencoded({
extended: true
});
app.use(bodyParser.json());
app.use(urlencoded_body_parser);
app.post("/save", function (req, res) {
console.log(req.body);
var student = new Student(req.body);
Student.findOne(req.body, function (err, success) {
if (err) {
console.log(err);
res.send(err);
}
else {
console.log(success);
if (success == null) {
student.save(function (err, success) {
if (err) {
console.log(err);
res.send(err);
}
else {
console.log("inserted");
console.log(success);
res.send("success");
}
});
} else {
res.send("Student already present");
}
}
})
});
app.listen(3000);
出力: -
初めて実行: -
入力: -
{
"name" : "john"
}
出力: -
0同じ入力JSONと
success
後続の実行: -
出力: - インデックスを使用しないのはなぜ
Student already present
?。それはずっと速いでしょう。重複を決定するフィールドにユニークなインデックスを作成します。これを確認してくださいhttps://docs.mongodb.com/manual/core/index-unique/#index-type-unique – RaR
答えが有用かどうか疑問に思っていますか? – notionquest