【问题标题】:Writing mongoDb queries using mongoose to create node api使用 mongoose 编写 mongoDb 查询以创建节点 api
【发布时间】:2016-09-21 16:32:48
【问题描述】:

我有一些 mongoDb 集合 'classrooms' 和 'students' 的形式: 教室:

{ 
    "_id" : ObjectId("56c7219dbd5f92cd78ae4b7e"), 
    "name" : "My Students", 
    "user" : ObjectId("56c7218cbd5f92cd78ae4b7c"), 
    "updatedAt" : ISODate("2016-02-19T14:07:25.965+0000"), 
    "createdAt" : ISODate("2016-02-19T14:07:25.965+0000"), 
    "students" : [
        ObjectId("56dbb26cff34aa686c0d9d25"), 
        ObjectId("56f7c2bf1982aa9219ae8843")
    ], 
    "role" : "user", 
    "allowDelete" : false, 
    "__v" : NumberInt(0)
}

学生:

{ 
    "_id" : ObjectId("56dbb26cff34aa686c0d9d25"), 
    "email" : "1989manjari@gmail.com", 
    "createdBy" : ObjectId("56c7218cbd5f92cd78ae4b7c"), 
    "classRoom" : ObjectId("56c7219dbd5f92cd78ae4b7e"), 
    "mentorEmail" : "gauravatbits@gmail.com", 
    "studentId" : ObjectId("56ced54303b7cb7b0eda9862"), 
    "status" : true, 
    "updatedAt" : ISODate("2016-03-11T15:32:36.806+0000"), 
    "autoAdd" : true, 
    "createdAt" : ISODate("2016-03-06T04:30:36.073+0000"), 
    "__v" : NumberInt(0)
}

我的查询是:

id_list = db.classrooms.distinct("students");
db.students.find({_id: {$in: id_list}, studentId:{$exists:false}},{email:1, mentorEmail: 1}).pretty()

现在我想在节点 api 中为此响应创建一个端点。所以我想知道如何在 Mongoose 中编写这些查询并创建如下端点:app.get('/api/myquery') 以获取 json 结果。

附: :是否可以这样做,而无需在 Mongoose 中创建模式,因为我也有一些没有大的集合。字段(38 个字段)。我只想通过在现有集合中应用查询来获取一些 json 数据。

【问题讨论】:

    标签: json node.js mongodb mongoose


    【解决方案1】:

    像猫鼬这样的东西

    只是伪代码

    var model = mongoose.model("collection", mongooseSchema)
    
    app.get('/api/myquery', function(){
        model.find({_id : id_list}, "email mentorEmail", function(err, data){
           if(err)throw err;
           res.json(data) // maybe use JSON.stringify() if didnt get json but that sets application/json in header of HTTP
        })
    })
    

    【讨论】:

      【解决方案2】:

      您可以直接在 mongoose 中插入 json,但您应该记住,只会读取 mongoose 模型中提到的数据。保留38个字段不是问题,直接插入即可。

      【讨论】:

        猜你喜欢
        • 2015-08-09
        • 1970-01-01
        • 1970-01-01
        • 2020-03-24
        • 2020-02-08
        • 1970-01-01
        • 2020-06-09
        • 2015-01-16
        • 2018-06-15
        相关资源
        最近更新 更多