[英]Integration Testing Nodejs/Express/Mongoose with Jest/Supertest One Mongoose Model Saves, One Mongoose Model Doesn't
[英]Update model with Mongoose, Express, NodeJS
我正在尝试更新 MongoDB 中的实例化模型('Place' - 我知道它可以从其他路由运行),并且花了一段时间尝试正确执行此操作。 我还尝试重定向回查看“地点”的页面以查看更新的属性。
Node v0.4.0、Express v1.0.7、Mongoose 1.10.0
架构:
var PlaceSchema = new Schema({
name :String
, capital: String
, continent: String
});
控制器/路由:
app.put('/places/:name', function(req, res) {
var name = req.body.name;
var capital = req.body.capital;
var continent = req.body.continent;
Place.update({ name: name, capital: capital, continent: continent}, function(name) {
res.redirect('/places/'+name)
});
});
我尝试了很多不同的方法,但似乎无法得到它。
另外,我是不是如何声明三个 {name, capital, and continent} 变量阻止进一步的操作? 谢谢。 还感谢一般调试帮助。 Console.log(name) (在声明的正下方)不记录任何内容。
玉形态:
h1 Editing #{place.name}
form(action='/places/'+place.name, method='POST')
input(type='hidden', name='_method', value='PUT')
p
label(for='place_name') Name:
p
input(type='text', id='place_name', name='place[name]', value=place.name)
p
label(for='place_capital') Capital:
p
input(type='text', id='place_capital', name='place[capital]', value=place.capital)
p
label(for='place_continent') Continent:
p
textarea(type='text', id='place_continent', name='place[continent]')=place.continent
p
input(type="submit")
您必须在更新任何内容之前找到该文档:
Place.findById(req.params.id, function(err, p) {
if (!p)
return next(new Error('Could not load Document'));
else {
// do your updates here
p.modified = new Date();
p.save(function(err) {
if (err)
console.log('error')
else
console.log('success')
});
}
});
使用您拥有的相同设置在生产代码中为我工作。 您可以使用 mongoose 提供的任何其他查找方法代替 findById。 只需确保在更新文档之前获取文档。
现在,我认为你可以这样做:
Place.findOneAndUpdate({name:req.params.name}, req.body, function (err, place) {
res.send(place);
});
您也可以通过 id 找到:
Place.findOneAndUpdate({_id:req.params.id}, req.body, function (err, place) {
res.send(place);
});
所以现在你可以直接通过id查找和更新,这是针对Mongoose v4的
Place.findByIdAndUpdate(req.params.id, req.body, function (err, place) {
res.send(place);
});
只是提一下,如果您需要更新的对象,那么您需要传递{new: true}
类的
Place.findByIdAndUpdate(req.params.id, req.body, {new: true}, function (err, place) {
res.send(place);
});
我认为您的问题是您正在使用节点 0.4.0 - 尝试移动到 0.2.6,它应该可以工作。 在 github 上记录了一个问题,bodyDecoder 未填充节点 >= 0.3.0 中的 req.body.variable 字段。
你可以根据下图做类似的事情
更新:
在我的解决方案中:我创建了一个模型、控制器和路由来描述 Nodejs MVC 框架中的类似场景(interacting with MongoDB method like updating/creating data to the database)
,以 MongoDB 作为数据库
// user.js - this is the user model
const mongoose = require('mongoose')
const validator = require('validator')
const User = mongoose.model('User', {
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
password: {
type: String,
required: true,
minlength: 7,
trim: true,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Password cannot contain "password"')
}
}
},
age: {
type: Number,
default: 0,
validate(value) {
if (value < 0) {
throw new Error('Age must be a positive number')
}
}
}
});
module.exports = User
// userController.js**
exports.updateUser = async(req, res) => {
const updates = Object.keys(req.body)
const allowedUpdates = ['name', 'email', 'password', 'age']
const isValidOperation = updates.every((update) => {
allowedUpdates.includes(update))
if (!isValidOperation) {
return res.status(400).send('Invalid updates!')
}
try {
const user = await UserModel.findByIdAndUpdate(req.params.id,
req.body, { new: true, runValidators: true })
if (!user) {
return res.status(404).send({ message: 'You do not seem to be registered' })
}
res.status(201).send(user)
} catch (error) {
res.status(400).send(error)
}
}
// **router.js**
router.patch('/user/:id', userController.updateUser)
我希望这会帮助任何人,你也可以阅读更多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.