【发布时间】:2019-06-08 03:27:05
【问题描述】:
我已经使用猫鼬有一段时间了。我想知道我这样做是对是错,最佳做法是什么。
我正在做的是::
/* myModel.js */
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
// 1. 创建我的架构
const mySchema = new Schema({
name: String,
age: Number
});
// 2.想使用fetch操作 // 但是我已经为此创建了方法
mySchema.methods.fetchById = async function(){
return await myModel.findById(this._id);
}
// 3. 创建模型
module.exports = myModel = mongoose.model('myModel', mySchema);
/* myController.js */
const User = require('./myModel');
router.get('user/:id', async (req, res, next) => {
try {
let user = new User({
_id: req.params.id
})
res.status(200).json(await user.fetchById());
} catch (err) {
next(err);
}
})
【问题讨论】:
标签: node.js mongodb express mongoose nosql