使用mongoose更新,不返回任何错误但不更新 [英] Updating with mongoose, not returning any errors but neither updating
问题描述
我正在尝试用猫鼬学习CRUD。我只是错过了更新部分。我做错了什么?
I am trying to learn CRUD with mongoose. I am only missing the update part. What am I doing wrong?
MY MODEL
var mongoose = require('mongoose');
var testSchema = new mongoose.Schema({
name: String,
number: Number
});
mongoose.model('TestData', testSchema);
MY ROUTES
// get the models
var Test = mongoose.model('TestData');
PARAM
如果链接有'test'
作为url参数,它将查看对象是否存在于数据库中,否则返回错误。
PARAM
If the link has the 'test'
as a url parameter, it will look if the object exist in the database, else return errors.
router.param('test', function(req, res, next, id){
var query = Test.findById(id);
query.exec(function(err, test){
if(err){ return next(err); }
if(!test){ return next(new Error('can\'t find test')); }
req.test = test;
return next();
});
});
GET BY ID
/* GET testdata/:id */
router.get('/testingdata/:test', function(req, res, next){
req.test.populate('test', function(err, test){
res.json(test);
});
});
DELETE
/* DELETE testdata/:id */
router.delete('/testingdata/:test', function(req, res, next){
req.test.remove('test', function(err, test){
console.log('removed');
res.json(test);
});
});
我的问题
现在问题来了我的问题如果我尝试更新一个,我只是遗漏了一些东西。
MY PROBLEM
Now here comes my problem, if I try to update one, I am simply missing something.
/* PUT testdata/:id */
router.put('/testingdata/:test', function(req, res, next){
req.test.update('test',{$set: {name: 'new data'}} , function(err, test){
res.json(test);
});
});
我没有收到任何错误,但它既没有更新任何内容。它甚至返回了一些数据。
I am not getting any errors, but it is neither updating anything. It is even returning some data.
{
"ok": 0,
"n": 0,
"nModified": 0
}
推荐答案
尝试没有不需要的第一个参数( test
),因为 req.test
是测试的一个实例
model。
Try without unneeded first argument (test
), because the req.test
is an instance of the Test
model.
req.test.update({name: 'new data'} , function(err, test){
res.json(test); // test would be `1` if success
});
更新
方法不会返回对象,如果你想返回对象,那么使用 save
:
The update
method will not return object, and if you want to return object then use save
:
req.test.name = 'new data';
req.test.save(function(err, test){
res.json(test);
});
这篇关于使用mongoose更新,不返回任何错误但不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!