我在MongoDb上有如下结构的文档,

我在我的节点应用程序中使用了Mongoose version ^4.8.1。我为上述文档创建了3个模式模型,如下所示:
Event.js
var mongoose = require('mongoose');
var eventSchema = new mongoose.Schema({
description: {
type: String
},
end_time: {
type: Date
},
start_time: {
type: Date
},
name: {
type: String
},
place: {
type: mongoose.Schema.Types.ObjectId,
ref: 'place'
}
});
eventSchema.index({name: 'text'},{'place.location.country':"text"});
var Event = mongoose.model('events', eventSchema);
module.exports= Event;Place.js
var mongoose = require('mongoose');
var placeSchema = new mongoose.Schema({
name: {
type: String
},
location: {
type: mongoose.Schema.Types.ObjectId,
ref: 'location'
}
});
var Place = mongoose.model('place', placeSchema);
module.exports= Place;Location.js
var mongoose = require('mongoose');
var locationSchema = new mongoose.Schema({
city: {
type: String
},
latitude: {
type: String
},
country: {
type: String
},
located_in: {
type: String
},
state: {
type: String
},
street: {
type: String
},
zip: {
type: String
},
});
var Location = mongoose.model('location', locationSchema);
module.exports= Location;访问/query数据库的通用处理程序,
dbHandler.js
querandpoplulate : function(model,condition,options)
{
return new Promise(function(resolve, reject) {
options = options||{};
console.log("model is" + model);
model.find({}).populate('place').populate('location').exec(function(error, data) {
if (error)
console.log(error);
reject(error);
console.log(data);
resolve(data);
})
})
}以下是我的质疑,
dbHelper.querandpoplulate(mongoose.model('events'), {$text: {$search: searchString},'place.location.country': countryString},function(error,data){
callback(data);
});问:它不返回带有place和location的结果集,而是返回null in place字段。
发布于 2017-02-06 13:24:01
在我看来,您的文档被保存为embedded documents,而不是referenced documents。
要获取此类文档,不需要执行任何population操作。简单的find查询应该适用于您。
试试这个:
model.find({}).exec(function(error, data) {
if (error)
console.log(error);
reject(error);
console.log(data);
resolve(data);
})因为您不是将data保存在mongoDB中,而是只检索它。您需要定义与schema结构匹配的document。
正如与您讨论的,我认为您需要更改Schema,并将所有3 schemas合并到一个文件中(Event.js)。
var mongoose = require('mongoose');
var locationSchema = new mongoose.Schema({
city: {
type: String
},
//add other fields here
});
var placeSchema = new mongoose.Schema({
name: {
type: String
},
location: locationSchema
});
var eventSchema = new mongoose.Schema({
description: {
type: String
},
//add other fields here too
place: placeSchema
});
eventSchema.index({name: 'text'},{'place.location.country':"text"});
var Event = mongoose.model('events', eventSchema);
module.exports= Event;https://stackoverflow.com/questions/42068630
复制相似问题