首页 > 解决方案 > Mongo:集合缺少实例中的属性

问题描述

因此,我为一些调查创建了一个路由处理程序,这些调查通过调查实例发送给客户:

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本地运行并从mongoshell 中查看它。如果我在 MLab 中这样做了,dateSent并且_user会出现吗?有区别吗?不知道为什么我没有在集合中获得这些属性。

标签: node.jsmongodbmongooseaxios

解决方案


在您的架构中,Survey对于dateSent

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

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

应该只是一个默认值。


推荐阅读