我在本地运行mongo。在这里,我将条目插入到我的数据库中并验证它是否存在
MongoDB shell version: 3.2.9
connecting to: test
> use testing
switched to db testing
> db.vetschool.insert({name: 'My First Cat'})
WriteResult({ "nInserted" : 1 })
> db.vetschool.findOne()
{ "_id" : ObjectId("57c051cbd7bd69709fa7d98a"), "name" : "My First Cat" }
这里我定义我的模式并执行findOne()函数,该函数返回一个空值。虽然没有显示,但我确实需要在我的文档顶部使用mongoose。
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Successfully connected to MongoDB');
});
var kittySchema = mongoose.Schema({
name: String
});
var Kitten = mongoose.model('Kitten', kittySchema);
Kitten.findOne().exec(function(err, success){
console.log(success); //returns null
console.log(err); //returns null
})
这可能是太多的附加信息,但这是我启动服务器时的输出和输出的空值
[nodemon] starting `node server.js`
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
Listening on port 3000...
Successfully connected to MongoDB
null
null
答案 0 :(得分:1)
简短回答:您正在使用mongo手动将文档插入vetschool
集合,然后要求Mongoose在Kittens
集合中查找该文档。
长答案:Mongoose根据您传递的模式名称自动确定集合的名称。来自http://mongoosejs.com/docs/models.html:
The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database.
因此,如果您通过Mongoose做一些事情并手动完成某些事情,那么您可以确保集合名称匹配。