express中MongoDB查询问题
最近刚开始学express,在敲mdn的实践,想要小修改一下,遇上一点问题,先上代码:
//tagController.js:
const Tag = require('../models/tag');
exports.find_all = async (req, res, next) => {
let result = await Tag.find({});
debugger;
res.send(result);
};
///./models/tag
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
var TagSchema = new Schema({
context: String,
tagId: ObjectId
//tagId: {type: ObjectId, ref: 'Tag', required: true},
});
TagSchema
.virtual('url')
.get(function () {
return '/tag/' + this._id;
});
module.exports = mongoose.model('Tag', TagSchema, 'Tag');
//routes.js
const express = require('express');
const router = express.Router();
const tag_controller = require('../controllers/tagController');
router.get('/', tag_controller.find_all);
//Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://****************************/test?ssl=true&replicaSet=piggybank-shard-0&authSource=admin&retryWrites=true';
const options = {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
autoIndex: false, // Don't build indexes
reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0,
connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
// replicaSet: 'piggybank-shard-0',
// ssl: true,
// authSource: admin,
// retryWrites: true
};
mongoose.connect(mongoDB,options);
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
数据库连接应该是正常的,能往表里插入数据,查询有问题,想问下可能是哪里写的不对,多谢:)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我试了下你的代码,查询是可以的,你可以看下我下面的截图:
我代码是直接copy的你上面的代码来的(就不贴代码了),所以我估计你查询不到数据,要么是你所谓的插入了数据可能插入失败了(你看下是不是把数据插入到Tag里了),要么是没有插入成功数据。