我正在努力避免重复被保存在系统中,并且已经实现了这样的模型......
var mongoose = require('mongoose'),
ObjectId = mongoose.Schema.Types.ObjectId,
Schema = mongoose.Schema;
var User = require('../models/user.js');
var Stamp = new Schema({
name: {type: String, unique: true },
creatorId: {type: ObjectId, ref: 'User'},
dateAdded: {type: Date}
}, {collection: "stamps"});
Stamp.index({name: 'text'});
//to avoid duplicate names
Stamp.path('name').index({ unique: true });
module.exports = mongoose.model('Stamp', Stamp);
保存新邮票的代码:
var new_stamp = new Stamp ({
name: stampname,
creatorId: creatorId,
dateAdded: dateAdded
});
new_stamp.save(function(err, results){
if(!err) {
console.log('stamp has been added to the db');
} else {
console.log("Error creating stamp " + err);
}
});
如何停止保存重复项?