他の人と同じように、私は間違いなくMongooseJSをお勧めします。私が同様のスタックを学ぼうとし始めたとき、それは私を助けました。サーバーには、次のようなものがあります。
// Define schema
var userSchema = mongoose.Schema(
{ name: 'string',
description: 'string',
email: 'string',
date: { type: Date, default: Date.now },
});
// Instantiate db model
var User = mongoose.model('User', userSchema);
// POST from client
exports.addUser = function (req, res) {
// req.body contains the json from the client post
// as long as the json field names are the same as the schema field names it will map the data automatically
var newUser = new User(req.body);
newUser.save(function (err) {
if(err) {
return res.json({error: "Error saving new user"});
} else {
console.log("success adding new user");
res.json(newUser);
}
});
};
// PUT from client
exports.updateUser = function(req, body) {
// this contains the updated user json
var updatedUser = req.body;
// here we lookup that user by the email field
User.findOne({ 'email': updatedUser.email }, function (err, user) {
if(err) {
return res.json({error: "Error fetching user" });
}
else {
// we succesfully found the user in the database, update individual fields:
user.name = updatedUser.name;
user.save(function(err) {
if(err) {
return res.json({error: "Error updating user"});
} else {
console.log("success updating user");
res.json(updatedUser);
}
})
}
});
};
編集*どうやらMongooseには実際にはfindOneAndUpdateメソッドがあり、モデルを更新するために上記で書いたのと本質的に同じことを行います。あなたはそれについてここで読むことができます