mongodb在save或者insert的时候,怎么仅仅存入新数据,如果新数据与数据库的数据有重复则跳过?我在定义model的schema的时候给一个字段加了个unique:true,但是我在保存的时候,出错了。那么怎么做才能只插入新数据啊?
var ImgSchema = new Schema({
url: {type: String, unique: true, dropDups: true },
createdAt: { type: Date, default: Date.now },
});
var newImg = new Img({
url: imgURL
});
newImg.save(function(err, save){
if (++watingToBeSaved == imgs.length) {
callback(null, {status: 'success'});
}
if (err) {
callback(err, null);
};
});
更新数据的话用update方法,save它就认为你要存入新数据了吧
你可以使用upsert来做 只要把update的第三个参数设为true就行了
设置 unique: true
,然后在错误处理的时候忽略 err.code === 11000
的情况,这个错误码是 duplicate key 错误。