我试图将预先填充的数据粘贴到我的mongoDB数据库中,但是当我仅通过电子邮件和密码发送POST请求时,默认数据就没有进入那里。相反,我看到的是一个名为'thisiswhereIwantthetestdata'的空数组。
我尝试在顶层添加默认数据,当我仅使用电子邮件和密码发送POST请求时,该方法就可以正常工作。
知道我在做什么错吗?也许与我引用[testSchema]的方式有关?
const mongoose = require('mongoose');
const testSchema = new mongoose.Schema({
test: {
type: String,
default: 'default test'
},
test2: {
type: String,
default: 'default test 2'
}
})
const userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
thisiswhereIwantthetestdata: [testSchema]
});
答案 0 :(得分:1)
您可以使用以下这样的预保存钩子来完成此操作:
用户架构:
const mongoose = require("mongoose");
const testSchema = new mongoose.Schema({
test: {
type: String,
default: "default test"
},
test2: {
type: String,
default: "default test 2"
}
});
const userSchema = new mongoose.Schema({
email: {
type: String,
// unique: true,
required: true
},
password: {
type: String,
required: true
},
tests: [
{
type: testSchema,
default: testSchema
}
]
});
userSchema.pre("save", function(next) {
if (this.tests.length == 0) this.tests.push({});
next();
});
module.exports = mongoose.model("User", userSchema);
创建用户的示例路径:
router.post("/", async (req, res) => {
const result = await User.create(req.body);
res.send(result);
});
当您使用此正文向该路线发送发布请求时:
{
"email": "a@b.net",
"password": "123123"
}
响应将像这样,意味着默认值有效:
{
"_id": "5de6b94ad440d0337c8fd388",
"email": "a@b.net",
"password": "123123",
"tests": [
{
"test": "default test",
"test2": "default test 2",
"_id": "5de6b94ad440d0337c8fd389"
}
],
"__v": 0
}