Mongo:集合缺少实例的属性

时间:2018-10-13 02:50:01

标签: node.js mongodb mongoose axios

因此,我为一些带有调查实例发送给客户的调查创建了路由处理程序:

module.exports = app => {
  app.post('/api/surveys', requireLogin, requireCredits, async (req, res) => {
    const { title, subject, body, recipients } = req.body;

    const survey = new Survey({
      title,
      subject,
      body,
      recipients: recipients.split(',').map(email => ({ email: email.trim() })),
      _user: req.user.id,
      dateSent: Date.now()
    });

    // Great place to send an email!
    const mailer = new Mailer(survey, surveyTemplate(survey));
    try {
      await mailer.send();
      await survey.save();
      req.user.credits -= 1;
      const user = await req.user.save();
      res.send(user);
    } catch (err) {
      res.status(422).send(err);
    }
  });
};

我只开发了后端,所以我不得不进入我的React前端并将axios添加到我的window对象中,如下所示:

// Development only axios helpers - do not push to production!
import axios from 'axios';
window.axios = axios;

然后在控制台中创建一个调查对象:

const survey = { title: 'my title', subject: 'Give Us Feedback' , recipients: 'renaissance.scholar2012@gmail.com', body: 'We would love to hear if you enjoyed our services' };
undefined

survey
{title: "my title", subject: "Give Us Feedback", recipients: "renaissance.scholar2012@gmail.com", body: "We would love to hear if you enjoyed our services"}

axios.post('/api/surveys', survey);
Promise {<pending>}

已成功发送一封包含调查的电子邮件,但是如果您查看survey实例,然后查看该集合:

> db.surveys.find()
{ "_id" : ObjectId("5bc1579ec759e774e1bdf253"), "yes" : 0, "no" : 0, "title" : "my title", "subject" : "Give Us Feedback", "body" : "We would love to hear if you enjoyed our services", "recipients" : [ { "responded" : false, "_id" : ObjectId("5bc1579ec759e774e1bdf254"), "email" : "renaissance.scholar2012@gmail.com" } ], "_user" : ObjectId("5ad25c401dfbaee22188a93b"), "__v" : 0 }
>

dateSent丢失:

          dateSent: Date.now()

我正在本地运行mongod,并从mongo shell进行查看。如果我已经在MLab中完成此操作,那么dateSent_user是否会出现?有区别吗?不知道为什么我没有在集合中得到那些属性。

1 个答案:

答案 0 :(得分:0)

Survey的架构中,dateSent的内容如下:

var YourSchema = new Schema({
  dateSent: {
    type: Date
    default: Date.now
  }
}

如果您不想这样,则不必设置该日期。在您提供的示例中,根本不需要处理该日期。

Should be just a default.