node.js - 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
本地运行并从mongo
shell 中查看它。如果我在 MLab 中这样做了,dateSent
并且_user
会出现吗?有区别吗?不知道为什么我没有在集合中获得这些属性。
解决方案
在您的架构中,Survey
对于dateSent
:
var YourSchema = new Schema({
dateSent: {
type: Date
default: Date.now
}
}
这样,如果您不想,您就不必设置该日期。在您给出的示例中,根本不需要处理该日期。
推荐阅读
- python - python tkinter中的标签
- javascript - 限制对用户 Node.js 的访问
- c# - newtonsoft json模式反序列化ValidationError
- angular - 如何修复类型“未知”不能用作索引类型
- reactjs - 如何在我的所有组件都安装在 React 中之前有一个加载屏幕
- r - 如何设置千位逗号分隔符作为 R 中的解释器如何呈现数字的默认选项?
- mongodb - 使用 mongoose 进行排序时考虑字符集
- python - 烧瓶中只有一个按钮发送两种表格
- php - laravel 的参数太少
- sql - 如何删除队列消息而不在 SQL Server 2014 中存储日志信息