Node.js 如何在mongodb中不将多个数据保存到集合中?
如果集合中已经存在数据,我不想再保存另一个数据。下面是一个简单的实现,说明如何防止在集合中已经存在文档时写入文档Node.js 如何在mongodb中不将多个数据保存到集合中?,node.js,mongodb,Node.js,Mongodb,如果集合中已经存在数据,我不想再保存另一个数据。下面是一个简单的实现,说明如何防止在集合中已经存在文档时写入文档 Collection.find( {}, (err, docs) => { // By not giving any arguments inside "{}", you tell MongoDB to return all the documents. if(docs) { // If there are any documents already present
Collection.find( {}, (err, docs) => { // By not giving any arguments inside "{}", you tell MongoDB to return all the documents.
if(docs) { // If there are any documents already present in the Collection, this will become true and nothing will happen.
return;
} else { // If there's no document already present in the Collection, new document will be added.
Collection.save(doc);
}
} );
您尝试了什么??当新对象插入mongoDb表时,该记录/对象会创建自己的id来标识唯一的行。这就像主键。目前我正在做的是正常的mongoose saveThanyou来回答!!如果此问题对开发者社区有帮助,请单击向上箭头接受此问题。