简体   繁体   中英

Select all the fields in a mongoose schema

I want to obtain all the fields of a schema in mongoose. Now I am using the following code:

let Client = LisaClient.model('Client', ClientSchema)
let query = Client.findOne({ 'userclient': userclient })
query.select('clientname clientdocument client_id password userclient')
let result = yield query.exec()

But I want all the fields no matter if they are empty. As always, in advance thank you

I'm not sure if you want all fields in a SQL-like way, or if you want them all in a proper MongoDB way.

If you want them in the proper MongoDB way, then just remove the query.select line. That line is saying to only return the fields listed in it.

If you meant in a SQL-like way, MongoDB doesn't work like that. Each document only has the fields you put in when it was inserted. If when you inserted the document, you only gave it certain fields, that document will only have those fields, even if other documents in other collections have different fields.

To determine all available fields in the collection, you'd have to find all the documents, loop through them all and build an object with all the different keys you find.

If you need each document returned to always have the fields that you specify in your select, you'll just have to transform your object once it's returned.

const fields = ['clientname', 'clientdocument', 'client_id', 'password', 'userclient'];
let Client = LisaClient.model('Client', ClientSchema)
let query = Client.findOne({ 'userclient': userclient })
query.select(fields.join(' '))
let result = yield query.exec()
fields.forEach(field => result[field] = result[field]);

That forEach loop will set all the fields you want to either the value in the result (if it was there) or to undefined if it wasn't.

MongoDB is schemaless and does not have tables, each collection can have different types of items.Usually the objects are somehow related or have a common base type.

Retrive invidual records using

db.collectionName.findOne() or db.collectionName.find().pretty()

To get all key names you need to MapReduce

mapReduceKeys = db.runCommand({
  "mapreduce": "collection_name",
  "map": function() {
      for (var key in this) {
          emit(key, null);
      }
  },
  "reduce": function(key, stuff) {
      return null;
  },
  "out": "collection_name" + "_keys"
})

Then run distinct on the resulting collection so as to find all the keys

db[mapReduceKeys.result].distinct("_id") //["foo", "bar", "baz", "_id", ...]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM