在express node.js的控制台上打印mongoose结果的值

oewdyzsn  于 2023-03-30  发布在  Go
关注(0)|答案(2)|浏览(177)

我正在通过查询从mongoose获取值

console.log(docs);
output :  [ { usercount: 0, _id: 5653fab1d6b5f1cf624b97fd },
         { usercount: 1, _id: 56541b49d6b5f1cf624b97ff } ]

       console.log(docs[1]._id);
output:   56541b49d6b5f1cf624b97ff

      console.log(docs[1].usercount);
output: undefined

那么,我将如何获得usercount的值。
我有模型uservisitcount.js,代码如下:

var mongoose = require('mongoose')
  ,Schema = mongoose.Schema
  uservisitcountSchema = new Schema( {
      usercount:String,
  }),
Usercount = mongoose.model('uservisitcount', uservisitcountSchema);

module.exports = Usercount;

在控制器中包含此型号,具有:

var Uservisitcount = require('../models/uservisitcount');

我运行了以下查询:

Uservisitcount.find({},function(err,docs){
       console.log(docs);
       console.log(docs[1]._id);
       console.log(docs[1].usercount);
   }
vs3odd8k

vs3odd8k1#

对返回的数据应用JSON.stringify()

Uservisitcount.find({},function(err,docs){
  if (err) throw err;
  console.log(JSON.stringify(docs)); 
  // or: 
  console.log('%s', docs); 
}
brvekthn

brvekthn2#

安装mongoose库以执行此示例

$ npm install mongoose
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// define a Mongoose schema
const UserSchema = new Schema({
   name: String,
   email: String,
   age: Number
});

// create a Mongoose model
const User = mongoose.model('User', UserSchema);

// connect to MongoDB
mongoose.connect('mongodb://localhost/my_database', { useNewUrlParser: true });

// retrieve data from the User model and console log it
User.find({}, (err, users) => {
   if (err) {
       console.error(err);
   } else {
       console.log(users);
   }
});

如果您希望使用users[]进行特定的重新计算,则将使用index of 0打印第一条记录
示例:-users[0].name--将打印姓名users[0].email--将打印电子邮件users[0].age--将打印年龄

相关问题