These are chat archives for Automattic/mongoose

28th
Mar 2017
Yarik Genza
@yarikgenza
Mar 28 2017 10:15

Hi guys, i am new in node.js. Pls, help me.
So, I have this mongoose middleware:

schema.post('save', (doc, next) => {
    if (doc.request) {
      const Request = mongoose.model('Request');

      return Request
        .findOne({ _id: doc.request })
        .then((request) => {
          if (!request) {
            throw new Error('No request related to the bid');
          }
          doc.startDate = request.startDate;
          doc.save();
          next()
        });
    } else {
      next();
    }
  });

It works well. But..

I would like to replace save() with mongoose .update() method.

schema.post('save', (doc, next) => {
    if (doc.request) {
      const Request = mongoose.model('Request');

      return Request
        .findOne({ _id: doc.request })
        .then((request) => {
          if (!request) {
            throw new Error('No request related to the bid');
          }
          doc.update({}, {
            $set: { startDate: request.startDate },
          })
            .then(() => {
              next();
            });
        });
    } else {
      next();
    }
  });

This code doesn't work. There is not field "startDate" in bid document. What i am doing wrong? Thanks.

Syforce
@Syforce
Mar 28 2017 15:01
@yarikgenza why not use findOneAndUpdate instead ?