【问题标题】:Mongoose: I need subdocuments to generate "_id" instead of "id" to search through array of documentsMongoose:我需要子文档来生成“_id”而不是“id”来搜索文档数组
【发布时间】:2018-02-09 19:46:14
【问题描述】:

我正在关注 Simon Holmes 的“Getting MEAN”一书,但是,我偶然发现了一个关于子文档 ID 的问题。我正在尝试使用猫鼬文档提供的“MongooseDocumentArray.id(id) helper 函数在“位置文档”中请求“审阅文档”。但是,我的所有子文档都生成“id”,但前面提到的函数需要“_id”返回“空”对象。

功能说明:在数组项中搜索第一个与_id匹配的文档。

这里有什么问题?我的父文档是“位置”,它使用“_id”生成它的 id,这让我更加困惑......嵌套模式设置,从包含审查子文档的数据库中返回的位置对象以及执行查询的路由的控制器函数分别在下面的代码 sn-ps 中说明。

var mongoose = require("mongoose");

var reviewSchema = new mongoose.Schema({    
    author: String,
    rating: {type: Number, required: true, min: 0, max: 5},
    reviewText: String,
    createdOn: {type: Date, "default": Date.now}
});

var locationSchema = new mongoose.Schema({
    name: {type: String, required: true},
    address: String,
    rating: {type: Number, "default": 0, min: 0, max: 5},
    facilities: [String],
    coords: {type: [Number], index: "2dsphere"},
    reviews: [reviewSchema]   
});

mongoose.model('Location', locationSchema);

Returned Location object showing subdocuments containing id instead of _id

对于下面的sn-p,这是相关的路由:

router.get("/locations/:locationid/reviews/:reviewid", ctrlReviews.reviewsReadOne);



module.exports.reviewsReadOne = function(req, res){ 
if(req.params && req.params.locationid && req.params.reviewid){
    Loc.findById(req.params.locationid)
        .select("name reviews")
        .exec(function(err, location) {
            var response, review;
            if(location.reviews && location.reviews.length > 0){                    
                // This returns zero, because the function requires _id
                // but all subdocuments have path/properties called id
                review = location.reviews.id(req.params.reviewid);
                console.log(review);

                if(!review){
                    sendJsonResponse(res, 404, {
                        "message": "reviewid not found"
                    });
                } else {
                    response = {
                        location: {
                            name: location.name,
                            id : req.params.locationid
                        },
                        review: review
                    };
                    sendJsonResponse(res, 200, response);
                }
            }
    })
}

};

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    将您的架构更改为以下内容。

    var locationSchema = new mongoose.Schema({
        name: {type: String, required: true},
        address: String,
        rating: {type: Number, "default": 0, min: 0, max: 5},
        facilities: [String],
        coords: {type: [Number], index: "2dsphere"},
        reviews: [{
           author: String,
           rating: {type: Number, required: true, min: 0, max: 5},
           reviewText: String,
           createdOn: {type: Date, "default": Date.now
        }]    
    });
    

    【讨论】:

    • 我会在设法修复我的数据库连接后立即检查此解决方案,但在重新安装完整系统后重新连接时会出现一些问题。
    • 它不起作用。我仍然遇到同样的问题。任何其他想法将不胜感激,谢谢
    【解决方案2】:

    其实我正在看这本书,这本书很棒,提供了很多关于MEAN堆栈的简单和优化架构的信息,问题出在书中的代码使用时:

    $push:{reviews:{author: 'Simon Holmes',id:Objectid(),...

    在这段代码中使用 id 而不是 _id,所以正确的脚本是:

    db.locations.update({name:'Starcups'},{$push:{reviews:{author:'Simon Holmes',_id:ObjectId(),评分: 5,timestamp:new Date("Jul 16,2013"),reviewText:"多么棒的地方啊。我说不出好话"}}});

    "当通过 Mongo shell 添加新的子文档时,您需要将 id 指定为 _id。" (Holmes S.) https://forums.manning.com/posts/list/35152.page

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 2018-06-25
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多