我是 MongoDB 和 Vuejs 的新手。我不確定是否有可能我試圖為唯一值設定驗證,但不知何故它不起作用。
我從后端定義的架構:
const uuid = require("uuid");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let informationSchema = new Schema ({
_id: {type: String, default: uuid.v1},
firstName: {
type: String, required:true, trim: true, unique: true
},
lastName: {
type: String, required:true, trim: true, unique: true
}
});
module.exports = mongoose.model('informations', informationSchema)
我在前端的 Vuejs 中的操作表單:
<template>
<div class="row justify-content-center">
<div class="col-md-6">
<h3 class="text-center">Create Name</h3>
<form @submit.prevent="handleSubmitForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" v-model="name.firstName" required>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" class="form-control" v-model="name.lastName" required>
</div>
<button class="btn btn-danger mt-3">Create</button>
</form>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
name: {
firstName: '',
lastName: ''
}
}
},
methods: {
handleSubmitForm() {
let apiURL = 'http://localhost:3000/name';
axios.post(apiURL, this.student).then(() => {
console.log(res)
}).catch(error => {
console.log(error)
});
}
}
}
</script>
我的第一個插入資料:[{"firstName":"ABC", "lastName": "DCF"}]
我想插入第二個資料:firstName = "ABC",但姓 = "XYZ"。由于在后端定義的架構中設定了驗證(唯一),因此發生驗證錯誤。
我的預期輸出:
有沒有可能的方法:
- 如果我插入第一個資料,它將起作用。
- 如果我插入與第一個資料相同的第二個資料,則會發生驗證錯誤。
- 如果我插入僅與 lastName 不同的第三個資料,它將起作用。
非常感謝。
uj5u.com熱心網友回復:
首先,Mongo 和 Vue 是完全分離的,沒有任何關系。
回答您的問題,驗證失敗,因為您告訴 mongo“設定firstName并lastName作為唯一欄位”。但不是“將這些欄位設定為唯一在一起”。因此,當您添加名字時,第二次嘗試添加現有名稱firstName并失敗。
所以你可以創建一個唯一的索引:
informationSchema.index({ firstName: 1, lastName: 1 }, { unique: true });
并洗掉unique架構中的約束。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/354913.html
