从MongoDB控制台记录数据

时间:2018-10-18 14:24:58

标签: node.js mongodb

我仍在尝试理解Mongoose/Mongo

现在在终端中当我在终端中做类似的事情

use library 
show collections 
db.authors.find().pretty()

我在登录后得到了类似的内容

{
    "_id" : ObjectId("5bc8704f3a9828d5513505a2"),
    "name" : "Aman",
    "age" : "21",
    "__v" : 0
}
{
    "_id" : ObjectId("5bc870553a9828d5513505a3"),
    "name" : "Rohit",
    "age" : "20",
    "__v" : 0
}


{
        "_id" : ObjectId("5bc8704f3a9828d5513505a7"),
        "name" : "Aman",
        "age" : "21",
        "__v" : 0
    }
    {
        "_id" : ObjectId("5bc870553a9828d5513505a5"),
        "name" : "Rohit",
        "age" : "20",
        "__v" : 0
    }

现在,我想在NodeJ中拥有相同的数据,也就是说,我想查找名称为Rohit的任何地方,并希望将其与其他数据库或模式链接。

如何获得与通过在NodeJS的mongo终端窗口中运行上述给定命令而获得的输出相同的输出

显然做类似console.log(db.authors.find())的事情是行不通的,那我该怎么办?

1 个答案:

答案 0 :(得分:2)

这是我通常编写数据库查询的方式。

首先创建一个模型将遵循的模式。不用担心此架构很灵活,您可以随时更改它而不会影响旧数据。

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

var authorSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  age: {
    type: Number,
    default: 20
  }
});

接下来,根据您的架构创建模型。

var authorModel = mongoose.model('authorModel', authorSchema); 

最后查询模型并获取所需的值

authorModel.find(
        {
          name: 'Rohit'
        },
        function (err, result) {
          console.log(result)
         });

我将架构和控制器放在单独的文件中。您如何组织代码结构取决于您自己。

当我第一次学习在NodeJS上构建API时,我几乎遵循this blog。您可能会发现它也很有用!