Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在mongodb中不将多个数据保存到集合中?_Node.js_Mongodb - Fatal编程技术网

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来回答!!如果此问题对开发者社区有帮助,请单击向上箭头接受此问题。