gpt4 book ai didi

node.js - 无法读取mongo/node中的集合数据

转载 作者:太空宇宙 更新时间:2023-11-04 00:31:13 24 4
gpt4 key购买 nike

我正在 nodeJs 中尝试 mongoDB,但 mongodb 服务器上的数据库收集文件遇到问题。服务器被设置为窗口服务,因此它已启动并运行。我在运行时让 NodeJS 连接到它。我做了模拟示例并且它有效(我认为它设置正确)。

如果我想查看在nodejs中创建的集合,它会显示它们。如果我转到 mongodb 服务器数据库(data\db 文件夹),我会看到一个集合已创建。问题是,当我打开 cmd.exe 的另一个实例时,输入 mongodb 并想查看集合 db.collections-2 中的内容,返回的是 NaN。

我可能做错了什么,或者有一个我不知道的文件丢失。有人可以建议我并解释为什么我得到 NaN 吗?

nodejs代码如下。

var MongoClient=require('Mongodb').MongoClient,format = require('util').format;
var url = 'mongodb://localhost:27017/myproject';
MongoClient.connect(url,function(err,db){
if(err){
console.log(err);
}
else{
console.log("connected to", url );
}
var user1 = {name: 'modulus admin', age: 42, roles: ['admin', 'moderator', 'user']};
var user2 = {name: 'modulus user', age: 22, roles: ['user']};
var user3 = {name: 'modulus super admin', age: 92, roles: ['super-admin', 'admin', 'moderator', 'user']};

collection.find({name: 'modulus user', roles: 'user'}).toArray(function(err, result) {
if (err) {
console.log(err);
} else if (result.length) {
console.log('Found:', result);
} else {
console.log('No document(s) found with defined "find" criteria!');
}
})

db.close()
})

最佳答案

好的,您的问题中有一些不清楚的地方,让我尝试澄清一下:

您将无法直接在data/db中读取集合数据,您必须使用mongo shell。

在 mongo shell 中,我认为这就是您所说的“打开 cmd.exe 的另一个实例,输入 mongodb”,尝试输入以下命令:

 use myproject 
show collections
db.mycollection.find({}) //replace 'mycollection' by the name of the collection

这将向您显示集合“mycollection”的第一个文档。

但是,在您的 Node 代码中,您似乎没有定义集合名称?它应该看起来像这样:

 var collection = db.collection('mycollection')
collection.find({name: 'modulus user', roles: 'user'}).toArray(...

关于node.js - 无法读取mongo/node中的集合数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40879424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com