从MongoDB中的不同模型中获取数据

时间:2017-02-08 12:40:54

标签: javascript node.js mongodb mongoose es6-promise

我在使用mongodb中的不同模型获取数据时遇到问题,为了说明最好举个例子:

模型A:有id,名称,描述

模型B:有id,model_A_id,slug,photos

我要做的是从模型B获取3个最近的记录,以及来自模型A的相应数据,来自模型B文件,这是我尝试编码的示例

let number = parseInt('666', 10);

我可能会离开这里,但我希望我的问题可以为我找到答案让我走上正轨,谢谢你的帮助!

以下是模型架构的示例:

modelB.getLatest = function(limit){
	var results = q.defer();

	var limit = parseInt(limit) || 3;
	var resultsArr = [];

	modelB.find(function(err, modelB_Records) {
		if (err){
			results.reject(err);
		} 
		
		if (modelB_Records) {
			return modelB_Records;
		} 
	}).sort({'date': -1}).limit(limit).then(function(modelB_Records) {
		modelB_Records.forEach(function(record) {
			modelA.findById(modelB.model_A_id).then(function(modelA_Record) {
				var resultsObj = { modelB_data: record, modelA_data: modelA_Record};
				resultsArr.push(resultsObj);
			});
		});

		results.resolve(resultsArr);
	});

	return results.promise;
}

1 个答案:

答案 0 :(得分:0)

以下是您的更新型号:

// Create schema for A
var SchemaA = new mongoose.Schema({
    // No need to create _id manually, just use the ObjectId from MongoDB
    name: String,
    developer: String,
    floors: Number,
    completionYear: Number
});
// Make model of schema for A
var SchemaAModel = mongoose.model("SchemaA", SchemaA);
// Export the model so you can require it somewhere else
module.exports = SchemaAModel;

// Create schema for B
var SchemaB = new mongoose.Schema({
    userId: String,
    buildingId: {
        type: String,
        ref: "SchemaA" // Make a ref to A, this is the mongoose model value
    },
    date: String,
    title: String,
    description: String,
    comments: [],
    rating: []
});
// Make model of schema for B
var SchemaBModel = mongoose.model("SchemaB", SchemaB);
// Export the model so you can require it somewhere else
module.exports = SchemaBModel;

首先,您应该为第一个模型创建一些记录(A)。从使用Mongoose的Node创建它们时,将自动生成_id。接下来,为您的第二个模型创建一些记录(B)。设置buildingId时,您需要从模型A输入_id

E.g:

模型A的记录:

{
    _id: ObjectId("562f51655b05e93371af9291"),
    name: "Some name",
    developer: "Some developer",
    floors: 5,
    completionYear: 2017,
}

B型记录:

{
    userId: "Some user id",
    buildingId: "562f51655b05e93371af9291", // This is the _id from the record above
    date: "2017-02-08",
    title: "Some title",
    description: "Some description",
    comments: [],
    rating: []
}

当一切都在数据库中时,您可以这样查询:

SchemaBModel
    // You will need to update your find
    .find()
    // Set key(s) to populate
    .populate("buildingId")
    .exec()
    .then(function onSuccess(response) {
        // Here are your B items with populated A items
    });

你最后的回答如下:

{
    userId: "Some user id",
    buildingId: {
        _id: ObjectId("562f51655b05e93371af9291"),
        name: "Some name",
        developer: "Some developer",
        floors: 5,
        completionYear: 2017,
    },
    date: "2017-02-08",
    title: "Some title",
    description: "Some description",
    comments: [],
    rating: []
}