Я ищу решение 2 дня и ничего не могу найти. Я получил схему, которая имеет 2 встроенные схемы. Я хочу, чтобы одна из встроенных схем была уникальной. Я попытался предварительно сохранить промежуточное программное обеспечение, но оно не работает, как исключено
Теперь я добавил два условия перед функцией schema.save () для проверки, но ни одно из них не сработало. Они оба отправляют сообщение об ошибке обратно клиенту, но функция schema.save запускается и вставляет новый документ!
Я пытался использовать try-catch перед schema.save (), выполняющим функцию, но код никогда не выполнялсявыдает ошибку!
Заранее спасибо!
Я прилагаю схему и скрипты контроллера!
Это topic.js, файл схемы
var mongoose = require('mongoose');
var Bookmarks = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
link: {
type: String,
trim: true,
unique: true,
required: true
},
owner : {
type: [String],
trim: true,
required: true
},
tags: {
type: [String],
trim: true
},
image : {
type: String,
trim: true
},
created_at: {
type: Date,
default: Date.now,
required: true
},
modified_at: {
type: Date,
default: Date.now,
required: true
}
},{
versionKey: false // You should be aware of the outcome after set to false
});
var Groups = mongoose.Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: true
},
admin: {
type: String,
trim: true,
required: true
},
members: {
type: [String],
trim: true
},
bookmarks: {
type: [Bookmarks]
}
},{
versionKey: false // You should be aware of the outcome after set to false
});
// Setup Schema
var Topics = mongoose.Schema({
name: {
type: String,
required: true,
lowercase: true,
unique: true
},
// Group Types
groups: {
type: [Groups]
},
// Bookmarks type
bookmarks: {
type: [Bookmarks],
unique:true
}
},{
versionKey: false // You should be aware of the outcome after set to false
});
// Export User model
module.exports = mongoose.model('topic', Topics);
файл controller.js
// Add Bookmark on Topic
exports.addBookmark = function(req, res) {
Topic.findOneAndUpdate( { name: req.body.name} , { $addToSet: { bookmarks: req.body.bookmark } } , {upsert: true }, function(err, topic) {
if (err) {
res.json({
status: 400,
message: "This topic does not exists"
});
} else if ( topic == null || req.body.bookmark == null) {
res.json({
status: 400,
message: "Please, complete all fields."
});
} else {
let bookmark = req.body.bookmark;
let flag = false;
for (var i = 0; i < topic.bookmarks.length ; i++) {
if ( topic.bookmarks[i].link === req.body.bookmark.link ) {
flag = true;
res.json({
status: 400,
message: "This bookmark already exists on this topic"
});
return err;
}
}
if ( bookmark.title == "" || bookmark.title == undefined || bookmark.description == "" || bookmark.description == undefined || bookmark.link == "" ||
bookmark.link == undefined || bookmark.owner == "" || bookmark.owner == undefined ) {
res.json({
status: 400,
message: "Please, complete all required fields for bookmark."
});
return;
}
topic.save(function(err, flag) {
if (err) {
res.json({
status: 400,
message: err,
});
} else {
res.json({
status: 200,
message: "Bookmark added to your topic list."
});
}
});
}
});
};