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/tagconst 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.jsconst express = require('express');
const router = express.Router();
const tag_controller = require('../controllers/tagController');
router.get('/', tag_controller.find_all);
//Set up mongoose connectionvar 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:'));
数据库连接应该是正常的,能往表里插入数据,查询有问题,想问下可能是哪里写的不对,多谢:)
回答:
我试了下你的代码,查询是可以的,你可以看下我下面的截图:
我代码是直接copy的你上面的代码来的(就不贴代码了),所以我估计你查询不到数据,要么是你所谓的插入了数据可能插入失败了(你看下是不是把数据插入到Tag里了),要么是没有插入成功数据。
以上是 express中MongoDB查询问题 的全部内容, 来源链接: utcz.com/p/197698.html