我正在使用一段非常标准的代码,在这里我正在定义一个模型
const mongoose = require('mongoose');
const Schema = new mongoose.Schema({
"id": String,
"country": String,
"city": String
}, {
versionKey: false,
timestamps: true
});
module.exports = mongoose.model('User', Schema);
然后我尝试使用请求正文来填充它
router.post("/", (req, res) => {
let user = new User(req.body);
user.save().then(() => {
res.send(user);
console.log(req.body, user);
}, () => {
res.end()
});
});
我在控制台中观察到以下输出
{
country: 'US',
city: 'New York'
} { _id: 60edf04ba78c881cb01e4866 }
如果我在 mongo 中检查我的收藏,我确认只有 id 被持久化。
我尝试从架构中删除“id”属性,但没有任何区别。
如何使用提供的数据填充我的模型?
答案 0 :(得分:0)
要使用信息填充您的模型,请使用 req.body
和 model.save()
方法。举个例子:
const {title, github, descrpition} = req.body;
const project = new Project({
title,
github,
description
})
return project.save().then(() => {
return res.status(200).send(project)
}).catch(err => console.log(err))
}
请记住,您必须拥有某种 json 解析器,例如 body-parser 或只是简单的 express