我正在尝试将文档保存到其他模型,然后再删除它。但是我无法使其正常工作。这是我所做的事情的代表。
架构
我创建了一个猫鼬模式,并从中创建了两个模型。
const Schema = mongoose.Schema;
const AccountSchema = new Schema({
fullname: {
type: String,
trim: true
// required: true
},
username: {
type: String,
trim: true,
unique: true,
required: true
},
email: {
type: String,
trim: true,
unique: true,
match: [/.+\@.+\..+/, "Please enter valid email!"],
required: true
},
password_hash: {
type: String,
unique: true,
required: true
},
salt: String,
created: {
type: Date,
default: new Date()
},
updated: Date,
updateCount: { type: Number, default: 0 }
});
创建模型
const AccountModel = mongoose.model("AccountModel", AccountSchema);
const AccountModel_deleted = mongoose.model("AccountModel_deleted", AccountSchema);
然后,我为url参数创建了一个函数,该函数根据其ID返回用户信息。示例:(/api/users/:the_id
)
const the_id = (req, res, next, id) => {
AccountModel.findById(id, (err, user) => {
if (err) {
return res.status(400).json({
error: "Cannot retrieve user with that id!"
});
}
req.userinfo = user;
next();
});
};
我尝试使用以下方法将上述方法(the_id
)发送的数据保存到数据库中:
// MOVE BEFORE DELETE
const move_to_deleted = (req, res, next) => {
const { _id, ...selected_user } = req.userinfo.toObject();
const moved = new AccountModel_deleted(selected_user);
moved.save((err, result) => {
if (err) {
return res.status(400).json({
error: err
});
}
res.json({
message: "Saved to database!"
});
});
// End moving
next();
};
通过此路由调用该方法:
router.route("/api/users/:the_id").post(move_to_deleted);
并使用以下方法执行它:
fetch("/api/users/" + _id, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + this.loginInfo.token
},
body: JSON.stringify(data)
})
.then(response => {
console.log(response);
})
.catch(e => console.log(e));
但是失败了。它不会保存并返回以下消息:
Response { type: "basic", url: "http://localhost:3000/api/users/5c96fd6855040e2884efc097", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
我实际上想将已删除的帐户/用户数据保存到其他集合中。但是我仍然不了解模型和集合之间的区别。因此,如果您也能解释一下,那就太好了。