3

These days I am reading mongoose documentation (https://mongoosejs.com/docs/queries.html), and there is something I cannot understand.

When executing a query with a callback function, you specify your query as a JSON document. The JSON document's syntax is the same as the MongoDB shell.

var Person = mongoose.model('Person', yourSchema);

// find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
  if (err) return handleError(err);
  // Prints "Space Ghost is a talk show host".
  console.log('%s %s is a %s.', person.name.first, person.name.last,
    person.occupation);
});

I cannot fully understand the meaning of "you specify query as a JSON document".

I thought it would be more relevant to saying "javascript object" rather than "JSON document".

According to Javascript object Vs JSON,

JSON is just a data interchange format.

So If we specify query as a JSON document, as mongoose documentation specifies, the querying would be like below.

// JSON.stringify({ 'name.last': 'Ghost' }) equals to "{ 'name.last': 'Ghost' }"
Person.findOne("{ 'name.last': 'Ghost' }", 'name occupation', function (err, person) {
  if (err) return handleError(err);
  // Prints "Space Ghost is a talk show host".
  console.log('%s %s is a %s.', person.name.first, person.name.last,
    person.occupation);
});

Even worse, mongoose documentation says that we can use query builder like below.

Person.
  find({
    occupation: /host/,
    'name.last': 'Ghost',
    age: { $gt: 17, $lt: 66 },
    likes: { $in: ['vaporizing', 'talking'] }
  }).
  limit(10).
  sort({ occupation: -1 }).
  select({ name: 1, occupation: 1 }).
  exec(callback);

It is quite confusing that the querying is specified with just occupation, not the 'occupation' with the single quote, like 'name.last'.

Which point am I misunderstanding?

Appreciate for your help in advance.

jwkoo
  • 2,393
  • 5
  • 22
  • 35

0 Answers0