我正在使用 、 和 开发一个 REST API ,node.js
并且发现这在回调中有效express.js
MongoDB
mongoose.js
app.put('/api/users/:userId',function(req, res) { });
new User({ userId : requestData.userId}).findByUserId(function (err, users) {
if (err) {
response.status = 'Find Error';
response.error = err;
debug('ERROR: ', err);
res.send(response);
} else if (!users.length) {
response.status = 'Registered a new user...';
debug(response.status);
var newUser = extend(new User({ userId : requestData.userId, created : Date.now() }), requestData);
newUser.save(function (err, saveduser) {
if (err) {
response.status = 'Insert Error';
response.error = err;
debug('ERROR: ', err);
} else {
response.user = saveduser;
debug('New user saved: ', saveduser);
}
res.send(response);
});
} else {
response.status = 'Found registered user...';
debug(response.status);
if (users.length !== 1) {
response.status = 'Multiple Users error';
response.error = 'Found more than one user with userId: ' + requestData.userId;
response.user = users;
debug('ERROR: Duplicate entries for userId %s. Users are: ', requestData.userId, users);
res.send(response);
} else {
var existingUser = users[0];
existingUser.updated = Date.now();
response.user = existingUser;
existingUser.save(function (err, user) {
if (err) {
response.status = 'Insert Error';
response.error = err;
debug('ERROR: ', err);
} else {
response.user = user;
debug('User updated: ', user);
}
res.send(response);
});
}
}
我已经看到了这个upsert
选项,但无法真正理解它。
callback
这绝对不是正确的方法,考虑到基于模型和其中的error
论点,我还没有找到任何关于如何以正确的方式做这件事的好文章。
有人能指出我正确的方向吗?