var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var TestSchema = new Schema({
user_sid: {
type: String,
unique: true,
},
user_Date: {
type: Date,
default: Date.now
}
});
var model_name = 'taobao';
var TAOBAO = mongoose.model(model_name, TestSchema);
var taobao = new TAOBAO();
taobao.user_sid = 1;
taobao.save(function(err) {
if (err) {
console.log('save failed');
return ;
}
console.log('save success');
console.log(taobao.user_Date);
});
var taobao2 = new TAOBAO();
taobao2.user_sid = 1;
taobao2.save(function(err) {
if (err) {
console.log('save failed');
return ;
}
console.log('save success');
console.log(taobao2.user_Date);
});
我把user_sid 属性设置成了 unique , 虽然在存储的时候会进入报错,但是MongoDB中还是存在了2条数据。
有没有什么方法,可以保证第2条数据不存在于数据库中。(不选择保存前,find 一下)