Nodejs mongoose如何关联保存
Nodejs mongoose如何关联保存
我现在又两个model,book和file 如下: var mongoDoc = require(’./db’); var mongoose = mongoDoc.mongoose; var db = mongoDoc.db; // 书籍定义 var BookSchema = mongoose.Schema({ name: String, ename: String, price: String, discount: { type: String, default: ‘10’ }, secDiscount: { type: String, default: ‘10’ }, bookVersion: { type: Number, default: 1 }, isStore: Boolean, publicDate: Date, forwardSaleDate: Date, appriaseState: Number, // 是否推荐 idRecommanded: { type: Boolean, default: false }, // 编辑推荐指数 recommandedExponent: { type: Number, default: 0 }, storeNumber: Number, ISBN: String, pageNumber: Number, banding: Number, memo: String, createDate: { type: Date, default: new Date() }, keyword: String, authors: [{ type: mongoose.Schema.Types.ObjectId, ref: ‘author’ } ], translators: [{ type: mongoose.Schema.Types.ObjectId, ref: ‘translator’ } ], publicCompany: [{ type: mongoose.Schema.Types.ObjectId, ref: ‘publicCompany’ } ], bookCategray: [{ type: mongoose.Schema.Types.ObjectId, ref: ‘bookCategray’ } ], promotion: Boolean, promotionDepart: [{ type: mongoose.Schema.Types.ObjectId, ref: ‘promotionDepart’ } ], images: [{ type: mongoose.Schema.Types.ObjectId, ref: ‘file’ } ] }, { safe: { j: 1, w: 2, wtimeout: 20000 }, capped: { size: 1024, max: 100, autoIndexId: true } }); var BookModel = db.model(“book”, BookSchema); module.exports.BookModel = BookModel; module.exports.BookSchema = BookSchema;
var mongoDoc = require(’./db’); var mongoose = mongoDoc.mongoose; var db = mongoDoc.db; var FileSchema = mongoose.Schema({ url: String, // 使用场景 useType: { type: String }, name: String, memo: String, uploadDate: { type: Date, default: new Date() }, // 是否正在被使用中 isCurrentUsed: { type: Boolean, default: false }, // 文件类型==扩展名 type: { type: String }, filename: String, // mime类型 filetype: String, filesize: String, // 是否可以删除 canRemove: { type: Boolean, default: true }, // 是否可以移动 canChangeFolder: { type: Boolean, default: true }, // 是否可以重命名 canRename: { type: Boolean, default: true }, // 随机码 randomNumber: { type: String, default: Math.random() + ‘’ } }, { safe: { j: 1, w: 2, wtimeout: 20000 }, capped: { size: 1024, max: 100, autoIndexId: true } }); var FileModel = db.model(“file”, FileSchema); module.exports.FileSchema = FileSchema; module.exports.FileModel = FileModel;
操作方法: // 上传对应图书的图片信息 Book.prototype.uploadBookImage = function(bookid, attributes, callback) { var image = new FileModel({ name: attributes.name, memo: attributes.memo, useType: attributes.type, isCurrentUsed: attributes.isCurrentUsed ? attributes.isCurrentUsed : true, uploadDate: new Date(), filename: attributes.file.filename, filetype: attributes.file.filetype, filesize: attributes.file.filesize, filepath: attributes.file.filepath, type: attributes.file.filename.substring(attributes.file.filename.lastIndexOf(’.’) + 1) }); BookModel.findById(bookid) ; // 查找图书信息 BookModel.findById(bookid, function(err, book) { if (err) return callback(err); else { image.save(function(errr, img) { if (errr) { return callback(errr); } else { book.images = [img.id]; BookModel.update(book, { new: true, upsert: false }, function(err, book_) { if (err_) return callback(err_); return callback(err_, book_); }); } }); } }); }
为什么这样不能将file的关联关系保存到book中呢 有什么好的方法么
要将 File
模型中的文件与 Book
模型中的书籍关联起来,需要正确地将 File
的引用添加到 Book
的 images
字段中。以下是一个改进的方法来实现这一功能:
示例代码
首先,我们修改 uploadBookImage
方法以确保文件引用被正确保存。
const Book = require('./models/book'); // 假设你的 Book 模型在 models/book.js 中
const File = require('./models/file'); // 假设你的 File 模型在 models/file.js 中
Book.prototype.uploadBookImage = async function(bookid, attributes) {
try {
const file = new File({
name: attributes.name,
memo: attributes.memo,
useType: attributes.type,
isCurrentUsed: attributes.isCurrentUsed || true,
uploadDate: new Date(),
filename: attributes.file.filename,
filetype: attributes.file.filetype,
filesize: attributes.file.filesize,
filepath: attributes.file.filepath,
type: attributes.file.filename.substring(attributes.file.filename.lastIndexOf('.') + 1)
});
await file.save(); // 保存文件模型实例
const book = await Book.findById(bookid); // 查找图书信息
if (!book) {
throw new Error('Book not found');
}
// 将文件的 _id 添加到书的 images 数组中
book.images.push(file._id);
// 更新书籍模型
await book.save();
return { success: true, message: 'Image uploaded and associated with the book successfully' };
} catch (error) {
return { success: false, error: error.message };
}
};
解释
-
创建并保存文件:首先创建一个新的
File
实例,并将其保存到数据库中。这会生成一个唯一的_id
。const file = new File({ name: attributes.name, memo: attributes.memo, useType: attributes.type, isCurrentUsed: attributes.isCurrentUsed || true, uploadDate: new Date(), filename: attributes.file.filename, filetype: attributes.file.filetype, filesize: attributes.file.filesize, filepath: attributes.file.filepath, type: attributes.file.filename.substring(attributes.file.filename.lastIndexOf('.') + 1) }); await file.save();
-
查找书籍:使用
findById
方法找到对应的书籍。const book = await Book.findById(bookid); if (!book) { throw new Error('Book not found'); }
-
更新书籍的
images
字段:将新创建的文件的_id
添加到书籍的images
数组中。book.images.push(file._id);
-
保存更新后的书籍:调用
save
方法保存更新后的书籍模型。await book.save();
通过这种方式,你可以确保文件与书籍之间的关联关系被正确保存。
代码太不清晰了,要格式化
要在 Mongoose 中将 File
模型的文档关联到 Book
模型的 images
数组中,你需要正确地更新 Book
文档并保存它。以下是改进后的代码示例:
Book.prototype.uploadBookImage = function(bookid, attributes, callback) {
var image = new FileModel({
name: attributes.name,
memo: attributes.memo,
useType: attributes.type,
isCurrentUsed: attributes.isCurrentUsed || true,
uploadDate: new Date(),
filename: attributes.file.filename,
filetype: attributes.file.filetype,
filesize: attributes.file.filesize,
type: attributes.file.filename.substring(attributes.file.filename.lastIndexOf('.') + 1)
});
// 查找图书信息
BookModel.findById(bookid, async function(err, book) {
if (err) return callback(err);
try {
await image.save(); // 保存图片信息
book.images.push(image._id); // 将图片ID添加到books的images数组中
// 更新Book文档
await book.save();
callback(null, book);
} catch (error) {
callback(error);
}
});
};
解释
- 创建图片实例:首先创建一个新的
FileModel
实例。 - 查找书籍:通过
findById
方法查找对应的书籍。 - 保存图片:保存图片实例到数据库,并获取其
_id
。 - 更新书籍:将新图片的
_id
添加到书籍的images
数组中,并保存更新后的书籍。
通过这种方式,你可以确保图片信息正确保存,并且关联关系也能够正确保存到书籍中。