将数据从猫鼬模式检索到我的node js项目中

时间:2019-06-12 17:19:13

标签: node.js mongodb express

我正试图从猫鼬模式中检索我的数据到我的路线(例如像邮递员一样使用名为insomnia的应用程序),所以每当我运行要获取的路线并清空数组时,这是怎么回事?

app.js

const express=require('express');
const bodyparser=require('body-parser');
const app=express();


app.use(bodyparser.urlencoded({extended:false}));
const User=require('./db/models/user').User;
require('./db/mongo');

app.get("/api/user",function(req,res){
User.find().then(function(x){
res.send(x)
console.log(req.body)
})
})







app.listen(3000);

mongo.js

const mongoose = require('mongoose');
db=mongoose.connect('mongodb://localhost/chatter_dev', 
{useNewUrlParser:true});
var db = mongoose.connection;

db.once('open', function callback () {
console.log("h");
});
module.exports =mongoose;

user.js

const mongoose=require('mongoose');


const userschema=new mongoose.Schema({
username:{
    type:String,
    unique:true,
    required:true
},
email:{
    type:String
},
firstname:String,
lastname:String},{
timestamps:true}
)
exports.User=mongoose.model("User",userschema)

3 个答案:

答案 0 :(得分:1)

在进行任何工作以获取数据之前,必须先获取一些数据。进入mongo并手动插入一些记录。简单的步骤可以帮助您诊断问题。

答案 1 :(得分:0)

您可以尝试一下

 User.find((err, users) => {
    if (err) res.status(500).send(err);
    else res.json(users);
  });

答案 2 :(得分:0)

**App.js**

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const User = require('./models/users');


const options = {
    useNewUrlParser: true,
    useCreateIndex: true
};

mongoose.connect('mongodb://localhost/chatter_dev', options)
    .then(connected => console.log(`Database connection establised`))
    .catch(err => console.error(err));

app.get('/api/users', (req, res, next) => {
    User.find().then(user => res.send(user)).catch(err => console.error(err));
})

app.listen(3000);

**Users.js (model)**

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    username:{
    type:String,
    unique:true,
    required:true
    },
    email:{
    type:String
    },
    firstname:String,
    lastname:String
}, {timestamps: true});

module.exports = mongoose.model('User', userSchema);