MongoDB - 如何仅从特定字段获取内容
MongoDB - How to get content from a specific field only
仅在 Mongo 中从特定字段检索内容的最佳方法是什么?
使用 Mongoose,这是我的架构:
module.exports = mongoose => {
const Shop = mongoose.model(
'Shop',
mongoose.Schema(
{
cid: String,
title: String,
categoryName: String,
address: {
street: String,
city: String,
postalCode: Number,
country: String,
fullAddress: String,
},
website: String,
phone: String,
location: {
lat: Number,
lng: Number,
},
totalScore: Number,
reviewsCount: Number,
openingHours: [
{
day: String,
hours: String,
}
],
imageUrls: [{type: String}],
reviews: [
{
name: String,
text: String,
publishedAtDate: String,
stars: Number,
id: String,
}
],
}
)
)
return Shop;
}
我正在寻找 Mongoose 查询,例如仅返回城市。
这是我试过的功能,但是我不能让它工作...
const db = require('../models');
const Shop = db.shop;
const readCities = async(req, res) => {
try {
const cities = Shop.find({}).select('address.city');
console.log(cities);
res
.status(200)
.send(cities);
} catch (error) {
console.log('Error occured while retrieving cities... ', error);
res
.status(500)
.send(error);
}
}
编辑
按照建议,当我 运行 以下更新脚本时:
const readCities = async(req, res) => {
try {
const cities = Shop.find({}, { 'address.city' : 1});
console.log(cities);
res
.status(200)
.send('It works');
} catch (error) {
console.log('Error occurred while retrieving cities... ', error);
res
.status(500)
.send(error);
}
}
这是我得到的答案:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
modelName: 'Shop',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: {},
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'shops',
collectionName: 'shops',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 1,
_closeCalled: undefined,
_hasOpened: true,
plugins: [],
id: 0,
_queue: [],
_listening: false,
_connectionString: 'mongodb://192.168.1.211:27019/seox',
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
db: [Db],
host: '192.168.1.211',
port: 27019,
name: 'seox'
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Shop },
schema: Schema {
obj: {
cid: [Function: String],
title: [Function: String],
categoryName: [Function: String],
address: [Object],
website: [Function: String],
phone: [Function: String],
location: [Object],
totalScore: [Function: Number],
reviewsCount: [Function: Number],
openingHours: [Array],
imageUrls: [Array],
reviews: [Array]
},
paths: {
cid: [SchemaString],
title: [SchemaString],
categoryName: [SchemaString],
'address.street': [SchemaString],
'address.city': [SchemaString],
'address.postalCode': [SchemaNumber],
'address.country': [SchemaString],
'address.fullAddress': [SchemaString],
website: [SchemaString],
phone: [SchemaString],
'location.lat': [SchemaNumber],
'location.lng': [SchemaNumber],
totalScore: [SchemaNumber],
reviewsCount: [SchemaNumber],
openingHours: [DocumentArrayPath],
imageUrls: [SchemaArray],
reviews: [DocumentArrayPath],
_id: [ObjectId],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {
'openingHours.day': [SchemaString],
'openingHours.hours': [SchemaString],
'openingHours._id': [ObjectId],
'imageUrls.$': [SchemaString],
'reviews.name': [SchemaString],
'reviews.text': [SchemaString],
'reviews.publishedAtDate': [SchemaString],
'reviews.stars': [SchemaNumber],
'reviews.id': [SchemaString],
'reviews._id': [ObjectId]
},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: { address: true, location: true },
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: {
cid: [Function: String],
title: [Function: String],
categoryName: [Function: String],
address: [Object],
website: [Function: String],
phone: [Function: String],
location: [Object],
totalScore: [Function: Number],
reviewsCount: [Function: Number],
openingHours: [Array],
imageUrls: [Array],
reviews: [Array],
_id: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [ [Object], [Object] ],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
mapPaths: [],
s: { hooks: [Kareem] },
_userProvidedOptions: {},
options: {
typeKey: 'type',
id: true,
_id: true,
validateBeforeSave: true,
read: null,
shardKey: null,
discriminatorKey: '__t',
autoIndex: null,
minimize: true,
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: true,
strict: true,
pluralization: true
},
'$globalPluginsApplied': true
},
op: 'find',
options: {},
_conditions: {},
_fields: { 'address.city': 1 },
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: Collection {
collection: [Collection],
Promise: [Function: Promise],
modelName: 'Shop',
_closed: false,
opts: [Object],
name: 'shops',
collectionName: 'shops',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'shops'
},
_traceFunction: undefined,
'$useProjection': true,
_userProvidedFields: { 'address.city': 1 }
}
如何使用结果?即数据在哪里?
试试这个代码:
const readCities = async(req, res) => {
try {
const cities = await Shop.find({}, { 'address.city' : 1});
console.log(cities);
res
.status(200)
.send('It works');
} catch (error) {
console.log('Error occurred while retrieving cities... ', error);
res
.status(500)
.send(error);
}
}
仅在 Mongo 中从特定字段检索内容的最佳方法是什么?
使用 Mongoose,这是我的架构:
module.exports = mongoose => {
const Shop = mongoose.model(
'Shop',
mongoose.Schema(
{
cid: String,
title: String,
categoryName: String,
address: {
street: String,
city: String,
postalCode: Number,
country: String,
fullAddress: String,
},
website: String,
phone: String,
location: {
lat: Number,
lng: Number,
},
totalScore: Number,
reviewsCount: Number,
openingHours: [
{
day: String,
hours: String,
}
],
imageUrls: [{type: String}],
reviews: [
{
name: String,
text: String,
publishedAtDate: String,
stars: Number,
id: String,
}
],
}
)
)
return Shop;
}
我正在寻找 Mongoose 查询,例如仅返回城市。
这是我试过的功能,但是我不能让它工作...
const db = require('../models');
const Shop = db.shop;
const readCities = async(req, res) => {
try {
const cities = Shop.find({}).select('address.city');
console.log(cities);
res
.status(200)
.send(cities);
} catch (error) {
console.log('Error occured while retrieving cities... ', error);
res
.status(500)
.send(error);
}
}
编辑
按照建议,当我 运行 以下更新脚本时:
const readCities = async(req, res) => {
try {
const cities = Shop.find({}, { 'address.city' : 1});
console.log(cities);
res
.status(200)
.send('It works');
} catch (error) {
console.log('Error occurred while retrieving cities... ', error);
res
.status(500)
.send(error);
}
}
这是我得到的答案:
Query {
_mongooseOptions: {},
_transforms: [],
_hooks: Kareem { _pres: Map(0) {}, _posts: Map(0) {} },
_executionStack: null,
mongooseCollection: Collection {
collection: Collection { s: [Object] },
Promise: [Function: Promise],
modelName: 'Shop',
_closed: false,
opts: {
autoIndex: true,
autoCreate: true,
schemaUserProvidedOptions: {},
capped: false,
Promise: [Function: Promise],
'$wasForceClosed': undefined
},
name: 'shops',
collectionName: 'shops',
conn: NativeConnection {
base: [Mongoose],
collections: [Object],
models: [Object],
config: {},
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object: null prototype],
_readyState: 1,
_closeCalled: undefined,
_hasOpened: true,
plugins: [],
id: 0,
_queue: [],
_listening: false,
_connectionString: 'mongodb://192.168.1.211:27019/seox',
_connectionOptions: [Object],
client: [MongoClient],
'$initialConnection': [Promise],
db: [Db],
host: '192.168.1.211',
port: 27019,
name: 'seox'
},
queue: [],
buffer: false,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
}
},
model: Model { Shop },
schema: Schema {
obj: {
cid: [Function: String],
title: [Function: String],
categoryName: [Function: String],
address: [Object],
website: [Function: String],
phone: [Function: String],
location: [Object],
totalScore: [Function: Number],
reviewsCount: [Function: Number],
openingHours: [Array],
imageUrls: [Array],
reviews: [Array]
},
paths: {
cid: [SchemaString],
title: [SchemaString],
categoryName: [SchemaString],
'address.street': [SchemaString],
'address.city': [SchemaString],
'address.postalCode': [SchemaNumber],
'address.country': [SchemaString],
'address.fullAddress': [SchemaString],
website: [SchemaString],
phone: [SchemaString],
'location.lat': [SchemaNumber],
'location.lng': [SchemaNumber],
totalScore: [SchemaNumber],
reviewsCount: [SchemaNumber],
openingHours: [DocumentArrayPath],
imageUrls: [SchemaArray],
reviews: [DocumentArrayPath],
_id: [ObjectId],
__v: [SchemaNumber]
},
aliases: {},
subpaths: {
'openingHours.day': [SchemaString],
'openingHours.hours': [SchemaString],
'openingHours._id': [ObjectId],
'imageUrls.$': [SchemaString],
'reviews.name': [SchemaString],
'reviews.text': [SchemaString],
'reviews.publishedAtDate': [SchemaString],
'reviews.stars': [SchemaNumber],
'reviews.id': [SchemaString],
'reviews._id': [ObjectId]
},
virtuals: { id: [VirtualType] },
singleNestedPaths: {},
nested: { address: true, location: true },
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: {
cid: [Function: String],
title: [Function: String],
categoryName: [Function: String],
address: [Object],
website: [Function: String],
phone: [Function: String],
location: [Object],
totalScore: [Function: Number],
reviewsCount: [Function: Number],
openingHours: [Array],
imageUrls: [Array],
reviews: [Array],
_id: [Object],
__v: [Function: Number],
id: [VirtualType]
},
query: {},
childSchemas: [ [Object], [Object] ],
plugins: [ [Object], [Object], [Object], [Object], [Object] ],
'$id': 1,
mapPaths: [],
s: { hooks: [Kareem] },
_userProvidedOptions: {},
options: {
typeKey: 'type',
id: true,
_id: true,
validateBeforeSave: true,
read: null,
shardKey: null,
discriminatorKey: '__t',
autoIndex: null,
minimize: true,
optimisticConcurrency: false,
versionKey: '__v',
capped: false,
bufferCommands: true,
strictQuery: true,
strict: true,
pluralization: true
},
'$globalPluginsApplied': true
},
op: 'find',
options: {},
_conditions: {},
_fields: { 'address.city': 1 },
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: NodeCollection {
collection: Collection {
collection: [Collection],
Promise: [Function: Promise],
modelName: 'Shop',
_closed: false,
opts: [Object],
name: 'shops',
collectionName: 'shops',
conn: [NativeConnection],
queue: [],
buffer: false,
emitter: [EventEmitter]
},
collectionName: 'shops'
},
_traceFunction: undefined,
'$useProjection': true,
_userProvidedFields: { 'address.city': 1 }
}
如何使用结果?即数据在哪里?
试试这个代码:
const readCities = async(req, res) => {
try {
const cities = await Shop.find({}, { 'address.city' : 1});
console.log(cities);
res
.status(200)
.send('It works');
} catch (error) {
console.log('Error occurred while retrieving cities... ', error);
res
.status(500)
.send(error);
}
}