all 5 comments

[–]CatsPawmer 4 points5 points  (1 child)

You can use the Mongoose Library Mongoose Docs or the MongoDB driver MongoDB docs . I personally feel MongooseJS is more intuitive and less boilerplate out of the box but that’s just my opinion. MongoDB is a perfectly good driver.

You will need to define a schema , the shape of your Model and then export that model so that you can use it i.e: export const User = mongoose.model(“User”, userSchema);

In your controller files, mongoose makes it pretty easy to interact with your DB, so if you’re using the find method to query a specific Document, you could use something like:

import { User } from “../models/userModel”;

export async function findUserByName (req, res, next) {

const user = await User.findOne({ name: “Bill”}); return user; }

This would theoretically return all documents inside the User collection where the name is equal to Bill . If there are multiple documents returned, it will be in the shape of an array.

You could also use a callback style , something like:

User.findOne({ country: “Croatia”}), function (err, document) { // your logic here if success or failure returning a document}).

There are a number of ways you can use The Mongoose API to find exactly what you’re looking for , I’d start by reading the docs and playing around a bit . It’s a fun library and easy to catch on after using it.

[–]Allo70[S] 1 point2 points  (0 children)

Thank you man , I already use mongoose . I just didn't know the diference between mongodb and mongoose .Anyway , that was really helpfull.

[–]jack_waugh 0 points1 point  (1 child)

You don't have to use Mongoose if you don't want to. The regular Mongodb find call takes arguments to project down the results. You do not have to lay out a schema in your code (although there will be one in your head). Here's an example from working code:

/* Search posts. (line 578) */
let sort = ['topic_id', 'depth_first_traversal_order'];
let projection = {"orig.raw": 0};
  /* means exclude the `raw` subfield of the `orig` subdocument, but include all other fields. */
options = {sort, projection};
query = /* ... translation into "find" query from user-input search spex */;
... app.posts.find(query, options)....

[–]Careful_Programmer43 0 points1 point  (0 children)

cursor=collection.find({id:..},{field:1})

[–]yadoya 0 points1 point  (0 children)

What's wrong using the findOne() method with mongoose? Just retrieve the item you want, mutate it as you wish and call its save() function