在使用猫鼬的find()时遇到问题,使用它的正确方法是什么?



我目前正在使用mongoose和nodeJS学习MongoDB。我正在尝试将笔记存储到一个名为"笔记"的数据库中。为此,首先我像这样连接到数据库:

mongoose.connect(`mongodb+srv://pedro_yanez:${password}@fsopen-2021-project.ngteq.mongodb.net/note-app?retryWrites=true&w=majority`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
})

然后,我创建了一个注释模式和一个注释模型:

const noteSchema = new mongoose.Schema({
content: String,
date: Date,
important: Boolean
})
const Note = mongoose.model('Note', noteSchema)

然后,我将三个文档保存到数据库:

const note = new Note({
content: 'Note #N',
date: new Date(),
important: true
})
note.save().then(result => {
console.log('note saved!')
mongoose.connection.close()
})

这是成功的,因为我可以在MongoDB Atlas的集合上看到它们,但是当我尝试使用mongoose的find()方法查询上传的笔记时,如下所示:

Note.find({}).then(result => {
result.forEach(note => {
console.log(note)
})
mongoose.connection.close()
})

我得到以下错误:

node_modules/mongoose/lib/query.js:2151
return cursor.toArray(cb);
^
TypeError: cursor.toArray is not a function

请注意,我附上的代码来自HY的"全栈开放2021"课程,来自part3.c。

我还尝试使用find()与回调函数,如下所述:

Note.find({}, function (err, docs) {console.log(docs)});
mongoose.connection.close()

但是我得到'undefined'和另一个错误:

/node_modules/mongodb/lib/collection.js:238
throw new error_1.MongoInvalidArgumentError('Method "collection.find()" accepts at most two arguments');
^
MongoInvalidArgumentError: Method "collection.find()" accepts at most two arguments

我真的需要一个提示,我的实现出了什么问题,因为我已经和这个战斗了一整天!

我看到我们在Fullstack打开上进行相同的练习。我设法记下了所有的"笔记"。下面从https://mongoosejs.com/

快速入门mongoose.connect后:

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// Here I used the Model.find() at the end of the page and closed 
// the connection as they say in the lesson.
});

它在这里工作,希望它帮助。

相关内容

最新更新