These are chat archives for Automattic/mongoose

8th
Oct 2016
M.G.Husny Ahamed
@husni1992
Oct 08 2016 10:23
Do anyone know how search a text in many fields in a mongooose document?
LibraryModel.find({ $text: { $search: libraryName } })
.limit(20)
.exec(function (err, items) {
console.log("items", items);
});
this doesnt work
antonioaltamura
@antonioaltamura
Oct 08 2016 12:55
@husni1992 You have to create a text index to be able to use $text operator.
docs: https://docs.mongodb.com/manual/core/index-text/
LibraryModel.index({'$**': 'text'}); after the model definition should works
Rob
@robertwalsh0
Oct 08 2016 13:55
Hey Can someone please answer this simple question: when testing a node server with mongoose, is the suggested practice to open db, load factory data, run test then close the db connection for each test?
Or is the practice to not actually touch the fb at all?
Zach Sosana
@SOSANA
Oct 08 2016 16:18
OMG so glad there is this group! I have been ripping my hair out last few days trying to solve a problem, hoping someone can help a brotha out
any one out there, I am trying to save a photo to my local drive with multer to a PhotoPost schema, there is a populated field I am trying to update to the user schema, I think my problem is in which order to properly save this, I am using postman to test this
here is my user model
Zach Sosana
@SOSANA
Oct 08 2016 16:23
// ================================
// User Schema
// ================================
const UserSchema = new Schema({
  email: { type: String, lowercase: true, unique: true, required: true },
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  password: { type: String, required: true },
  role: { type: String, enum: ['User', 'Admin'], default: 'User' },
  photoPosts: [{ type: mongoose.Schema.Types.ObjectId, ref: PhotoPost }],
}, { timestamps: true });
here is my photopost model
// ================================
// PhotoPost Schema
// ================================
const PhotoPostSchema = new Schema({
  photo: { type: String },
  photoText: { type: String },
  filter: { type: String },
  status: { type: String, enum: ['Pending', 'Approved', 'Disapproved'], default: 'Pending' },
  meta: { upvote: { type: Number }, fav: { type: Boolean } },
  created_by: [{ type: Schema.ObjectId, ref: User }],
}, { timestamps: true });
here is my photopost controller and route
import User from '../user/userModel';
import PhotoPost from './photoPostModel';

// ========================================
// Add a photo post ~ Controller Action
// ========================================
export function addPhotoPost(req, res, next) { // eslint-disable-line
  // Check for photo post errors
  const photoFilename = req.file;
  const photoText = req.body.photoText;
  const filter = req.body.filter;
  const createdBy = req.body.created_by; // eslint-disable-line no-underscore-dangle

  // assign our user info
  const user = new User({ _id: req.id });

  // successfully backout if user does not provide photo and photoText
  /*
  if (!photoFilename || !photoText) {
    return res.status(422).send({ error: 'You must provide a photo and some info' });
  }
*/

  if (req.file) {
    console.log('Profile image uploaded'); // eslint-disable-line no-console
    const photoFilename = req.file;
  }

  const photopost = new PhotoPost({
    photo: photoFilename,
    photoText,
    filter,
    createdBy: user._id,
  });

  photopost.save((err, saved) => {
    console.log('I am working!!'); // eslint-disable-line no-console
    if (err) return console.error(err); // eslint-disable-line no-console
    res.status(200).json({ photopost: saved });
    next();
  });

  user.save((err, saved) => {
    console.log('look at me!!'); // eslint-disable-line no-console
    if (err) return console.error(err); // eslint-disable-line no-console
    res.status(200).json({ user: saved });
    next();
  });

/*
  PhotoPost
  .findOne()
  .populate('created_by')
  .exec((err, saved) => {
    console.log('look at me now!!'); // eslint-disable-line no-console
    if (err) return console.error(err); // eslint-disable-line no-console
    res.status(200).json({ PhotoPost: saved });
    next();
  });
  */
}


// ===================================================
// Get one approved photo post ~ Controller Action
// ===================================================
// export function getPhotoPost() {

// ===================================================
// Get all approved photo posts ~ Controller Action
// ===================================================
// export function getPhotoPosts()

// ===================================================
// Update a single photo post ~ Controller Action
// ===================================================
// export function updatePhotoPosts()
import { Router } from 'express';
// import passport from 'passport';
import multer from 'multer';
import * as PhotoPost from './photoPostController';
// import * as Auth from '../user/userController';
import '../../config/passport'; // requiring passportService

const uploads = multer({ dest: '../../uploads-deleteMeLater' }).single('photo'); // Handle file uploads;

const photoPostRoutes = new Router();
// const requireAuth = passport.authenticate('jwt', { session: false });
// const requireSignin = passport.authenticate('local', { session: false });

// =========================
// PhotoPost Routes
// =========================

// Add a new Photo Post
photoPostRoutes.route('/pp/photopost', uploads).post(PhotoPost.addPhotoPost);

// Get all Photo Posts
// Get one Photo
// Add a new Photo Post
// Delete a Photo Post

// photoPostRoutes.route('/createphotoposts').post(requireAuth, PhotoPost.createPhotoPosts);

export default photoPostRoutes;
I think the problem is the order in which to save, Do I save the photo, along with some text, then do next() then populate my user schema?
anyone out there that could help me?
Zach Sosana
@SOSANA
Oct 08 2016 16:45
jimCarrey.jpg
Zach Sosana
@SOSANA
Oct 08 2016 18:51

Hoping someone can help me. I can't seem to get multer to save a photo to my localdrive, save text from the photoText, and populate my User object or PhotoPost. I am using postman to test the api end points.

One of my problems is trying to figure out which operation to do first and how to pass this through when saving in my photo post controller.

I am open to mongoose pre or post hooks etc just not sure one to use when saving this. I would imagine we would first save our photo, text, etc then do a populate to update our schema. I was considering also how to assign roles and status with enums when saving but need to do this on a admin schema....hope you guys n gals can help and if more info is needed please comment below