和其他人一样,我肯定会推荐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 方法,它与我上面写的更新模型的功能基本相同。你可以在这里阅读