Categories
JavaScript Answers

How to add a timestamp field with Mongoose and JavaScript?

To add a timestamp field with Mongoose and JavaScript, we set the timestamps option to true.

For instance, we write

const mySchema = new mongoose.Schema({ name: String }, { timestamps: true });

to create a schema with the name string field.

We set timestamps to true to make it a timestamp field.

Categories
JavaScript Answers

How to fix Permission denied when installing npm modules in OSX?

To fix Permission denied when installing npm modules in OSX, we change the permission of the node_modules directory.

For instance, we run

sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

to run chown to get the user with whoami and then set the node_modules, bin, and share directories’ owner to the current user.

And then we install packages with

sudo npm install
Categories
JavaScript Answers

How to auto generate migrations with Node.js Sequelize CLI from Sequelize models?

To auto generate migrations with Node.js Sequelize CLI from Sequelize models, we run sequelize model:create.

For instance, we run

sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text

to create the MyUser model with the first_name, last_name, and bio fields.

Then a migration file will be created along with the model file.

Categories
JavaScript Answers

How to set up two different static directories in Node.js Express framework?

To set up two different static directories in Node.js Express framework, we call express.static.

For instance, we write

app.use("/public", express.static(__dirname + "/public"));
app.use("/public2", express.static(__dirname + "/public2"));

to call express.static to return 2 middlewares toi server the /public and /public2 folders as static directories.

And then we call app.use to use the middlewares to make the folders available via the /public and /public2 URLs.

Categories
JavaScript Answers

How to perform a full text search in MongoDB and Mongoose and JavaScript?

To perform a full text search in MongoDB and Mongoose and JavaScript, we set the $text.$search property.

For instance, we write

const schema = new Schema({
  name: String,
  email: String,
  profile: {
    something: String,
    somethingElse: String,
  },
});
schema.index({ name: "text", "profile.something": "text" })

to create the schema schema.

And we add an index to it by calling `schema.index with the fields we want to index.

We add 'text' indexes to the name and profile.something fields.

Then we do a fuzzy search with

MyModel.find({ $text: { $search: searchString } })
  .skip(20)
  .limit(10)
  .exec((err, docs) => {
    //...
  });

to call find with the $text.$search property set to the query we want to run.

And we get the results returned from docs.