首页 > 解决方案 > 为什么 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);

曲目收藏

标签: node.jsmongodbexpressmongoose

解决方案


您需要像这样将 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' });

推荐阅读