node.js - 为什么 mongoose.find 返回一个空数组
问题描述
我正在创建一个快递服务器,我试图在其中找到我的数据库中的曲目。即使我已经创建了模型来准确地了解数据库中的属性,它仍然会返回一个空数组。请帮忙
应用程序.js
require('./config/config');
require('./db');
var Track = require('./models/track.model');
const mongoose = require('mongoose'),
express = require('express'),
bodyParser = require('body-parser');
var app = express();
const connection = mongoose.connection;
connection.once('open', () => {
console.log('MongoDB database connection established successfully!');
});
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.get('/', function(req, res) {
Track.find({}, function(err, tracks) {
if (!err) {
console.log(tracks);
process.exit();
}
else {
throw err;
}
});
res.sendFile('index.html', {root: __dirname});
});
app.listen(process.env.PORT, ()=> console.log(`Server started at port: ${process.env.PORT}`));
track.model.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let Track = new Schema({
Position: {
type: Number
},
Track: {
type: String
},
Artist: {
type: String
},
Streams: {
type: Number
},
Url: {
type: String
},
Date: {
type: String
}
});
module.exports = mongoose.model('Track', Track);
解决方案
您需要像这样将 Schema 绑定到集合:
let Track = new Schema({
Position: {
type: Number
},
Track: {
type: String
},
Artist: {
type: String
},
Streams: {
type: Number
},
Url: {
type: String
},
Date: {
type: String
}
}, { collection : 'spotifyCharts' });
推荐阅读
- java - swagger 是否依赖于 jax-rs 或 spring mvc?
- .net - IIS 中托管的 Web 应用程序引发网关超时错误
- python - Python整数输入到相应的命令值
- python - 避免在更新参数中没有 .caption(或 user.id 或.....)时收到错误(“NoneType”类型的参数不可迭代)
- c - fscanf() 如何处理双精度值?
- javascript - JavaScript:从文件阅读器中提取 base64 字符串
- ios - 减少文本字段中左视图和光标之间的差距
- amazon-web-services - AWS Cognito 角色限制调用 Lambda 的权限
- javascript - 在移动设备上将按空格键更改为屏幕按钮
- sas - 如何读取流内数据