简体   繁体   中英

How to get the data back from mongoDB and display it properly?

After I get the data from mongoDB how can I display it.
FOR EXAMPLE I have a simple hbs template

//index.hbs
{{# each user}}                 
         <div >
            <h5>{{ user.firstName }}</h5>
         </div>
         <div >
            <h5>{{ user.lastName }}</h5>
         </div>     
{{/each}}

now I can get the records from mongoDB with find.()

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
mongoose.connect("connection string");
var userSchema = new Schema({
  "firstName":  String,
  "lastName": String,
  "locationID": Number
});

var User = mongoose.model("Users", userSchema);

User.find({ locationID: 1}).exec().then((data)=>{
console.log(data);
});

Also, how can I get all the data from the mongoDB. Not using the find(). to search the condition.

Don't pass condition on find() like

User.find({ locationID: 1}).exec().then((data)=>{
console.log(data);
});

simply use

User.find().exec().then((data)=>{
console.log(data);
});

This is cleaner code for retrieving all documents in a given collection. You should be able to test this in Postman to verify it gives you the results you need--that's why I included the res.status().json() at the end.

const getUsers = async (req, res, next) => {
    

    const users = await User.find().exec();
    res.status(200).json({
      status: 'success',
      results: doc.length,

      data: {
        data: users,
      },
    });
  };

Also just a note: Don't use var because it is bad practice. It causes scoping problems, clutters the global namespace, and is a source of errors. Use let or const. Also, when doing asynchronous operations, use async await because it makes the code a lot more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM