How to get Data from MongoDb using mongoose?

后端 未结 3 1376
温柔的废话
温柔的废话 2021-01-11 11:25

I just started learning MongoDB and mongoose. Currently I have the following structure:

database   -> skeletonDatabase
collection -> adminLogin
         


        
相关标签:
3条回答
  • 2021-01-11 11:44

    mongoose by default takes singular model names and pairs them with a collection named with the plural of that, so mongoose is looking in the db for a collection called "adminLogins" which doesn't exist. You can specify your collection name as the 2nd argument when defining your schema:

    var adminLogin = new Schema({
        username: String,
        password: String
    }, {collection: 'adminLogin'});
    
    0 讨论(0)
  • 2021-01-11 11:47

    first compile just one model with the schema as an argument

    var adminLogin = mongoose.model('adminLogin', adminLogin);

    in your code adminLogin does not exist, adminLoginModel does;

    after that ,instead to

    adminLogin.find({}, function(err, data){
            console.log(">>>> " + data );
        });
    

    try this

    adminLogin.find(function (err, adminLogins) {
      if (err) return console.error(err);
      console.log(adminLogins);
    

    is important the "s" because mongo use the plural of the model to name the collection, sorry for my english...

    0 讨论(0)
  • 2021-01-11 11:51

    Had a problem with injecting it within an express route for my api so I changed it thanks to @elkhrz by first defining the schema and then compiling that one model I want to then pull like so:

    app.get('/lists/stored-api', (req, res) => {
    
        Apis.find(function(err, apis) {
    
            if (err) return console.error(err);
    
            res.send(apis);
    
        });
    
    });
    
    

    I wouldn't send it to the body, I would actually do something else with it especially if you plan on making your API a production based application.

    Run through this problem and read up on possible proper ways of rendering your data: How to Pass Data Between Routes in Express

    Always a good idea to practice safe procedures when handling data.

    0 讨论(0)
提交回复
热议问题