Reading
suggest changeThese find calls use a callback. That works on Mongoose 6 and earlier. Mongoose 7 returns a promise and does not take the callback. require('models/auto') does not look in a project folder; the path below is relative to this file.
Getting every document in the collection:
var Auto = require('./models/auto')
Auto.find({}, function (err, autos) {
if (err) return console.error(err);
// will return a json array of all the documents in the collection
console.log(autos);
})
Reading data with a condition
Auto.find({countOf: {$gte: 5}}, function (err, autos) {
if (err) return console.error(err);
// documents whose countOf is greater than or equal to 5
console.log(autos);
})
The second argument is a projection: which fields to return.
Auto.find({},{name:1}, function (err, autos) {
if (err) return console.error(err);
// will return a json array of name field of all the documents in the collection
console.log(autos);
})
Finding one document in a collection.
Auto.findOne({name:"newName"}, function (err, auto) {
if (err) return console.error(err);
//will return the first object of the document whose name is "newName"
console.log(auto);
})
Finding one document by id. 123 only matches if _id is the number 123. The default _id is an ObjectId, so pass that id string instead.
Auto.findById(123, function (err, auto) {
if (err) return console.error(err);
// the document whose _id is 123, when _id is stored as that number
console.log(auto);
})
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents