使用mongoose访问现有的MongoDB集合

11 浏览
0 Comments

使用mongoose访问现有的MongoDB集合

我正在使用Nodejs构建一个应用程序,在服务器端需要对一个集合执行一些函数。我被告知使用mongoose来访问该集合。以下是我的代码:

        var mongoose = require('mongoose');
        var Schema = mongoose.Schema;
        mongoose.connect('mongodb://localhost/test', function(err){
            if(!err){
                console.log("没有错误!")
            }
        });
        var doc = mongoose.model('foo', 
                       new Schema({name : String}), 
                       'answers'); 
        doc.find({}, function(err,collection){ 
          console.log(collection)
        });

我想访问名为“answers”的集合数据,并对其进行一些更改,并将其发布到另一个集合。上面的代码打印了一个空数组。我非常感谢您的帮助。

0
0 Comments

问题的出现原因:在使用mongoose连接到mongodb数据库并访问现有的集合时,出现了错误。

解决方法:

1. 首先,需要使用require()方法引入mongoose模块。

2. 然后,创建一个mongoose的Schema对象,用于定义集合的结构。

3. 使用mongoose的connect()方法连接到mongodb数据库,其中传入的参数为数据库的URL。

4. 在connect()方法的回调函数中,判断是否连接成功,如果没有错误,则打印"no error!"的信息。

5. 接下来,使用mongoose的model()方法创建一个名为"answer"的集合,其中传入的参数为之前创建的Schema对象。

6. 最后,使用find()方法查询集合中的所有数据,并在回调函数中打印出查询结果。

以上就是使用mongoose访问现有mongodb集合的解决方法。

0