1.api.js
2.db.js
3.vue
4.Database
turn out:
The result obtained is an empty array, but both the link and the database are correct. Why is this? ? ?
滿天的星座2017-06-05 11:10:50
The crux of this problem, as @cheesekun said, is that mongoose will automatically change the collection name (first parameter) in the model to plural form.
Here I give my own experimental process and provide two solutions below.
I first created a simple project based on the meaning of the topic
app.js
const express = require('express');
const app = express();
app.use('/api',require('./router/api'));
app.listen(3000, () => {
console.log('Server is running!');
});
module/db.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/test');
mongoose.connection
.on('connected', _ => console.log('mongodb connect successed'))
.on('error', _ => console.log('mongodb connect failed'))
.on('disconnected', _ => console.log('mongodb connect disconnected'));
const Schema = mongoose.Schema;
const listSchema = new Schema({
name: String,
age: Number
});
const List = mongoose.model('list', listSchema);
module.exports = {
List
}
router/api.js
const express = require('express');
const db = require('../module/db');
const router = express.Router();
router.get('/list', (req, res) => {
db.List.find((err,data)=>{
if(err){
console.log(err);
}else{
res.json(data);
}
});
});
module.exports = router;
Connect to mongodb through the visualization tool and insert a document under the test database list collection in advance
Find the reason
Insert a piece of data
through code at the bottom of
module/db.js
Re-running and accessing through the browser returned the data inserted through the codeconst list = new List({
name: '代码创建的数据',
age: 1
});
list.save(function (err, data) {
console.log(data);
});
At this time, you can find through the visualization tool that there is an additional collection
, and the data we inserted through the code is in it
Solution
If you do not specify the collection name explicitly, mongoose will automatically change the first parameter in model() to plural form as the collection nameProvide two solutions, both specify the collection name
The first type:
Pass the third parameter to mongoose.model() to specify the collection name
The second type: const List = mongoose.model('list', listSchema,'list');
const listSchema = new Schema({
name: String,
age: Number
},{
collection: 'list'
});
伊谢尔伦2017-06-05 11:10:50
I bet 50 cents. mongoose
When defining the model, s will be automatically added to the table name, but your login and list do not add s
The database cannot be called
This is a blog I wrote before, and it is mentioned at the bottom
mongoose deep sea pit
某草草2017-06-05 11:10:50
First of all, directly check whether the xhr return value in the console has a value. If there is a value, it means that you obtained it incorrectly.
If not, it means you didn’t send the value at all, which means the problem occurs in the backend, and you can go back and check.