您可以使用Mongoose的findOneAndUpdate
方法来更新数据库中的数组,并将随机化后的数组保存在其中。以下是一个示例代码:
首先,确保已安装和导入所需的依赖项:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
然后,创建一个包含数组的模式:
const randomArraySchema = new Schema({
array: {
type: [String],
required: true
}
});
接下来,创建模型并定义一个用于更新数组的路由:
const RandomArray = mongoose.model('RandomArray', randomArraySchema);
app.put('/randomize-array', async (req, res) => {
try {
const randomArray = await RandomArray.findOneAndUpdate(
{},
{ array: shuffleArray(req.body.array) }, // 使用shuffleArray函数来随机化数组
{ new: true, upsert: true }
);
res.send(randomArray);
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
在上面的示例中,我们使用findOneAndUpdate
方法来查找并更新数据库中的数组。如果找到匹配的文档,则更新该文档的数组字段。否则,使用upsert
选项创建一个新文档,并将随机化后的数组保存在其中。new:true
选项确保返回更新后的文档。
最后,编写一个函数来随机化数组:
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
以上是一个基本的解决方法,您可以根据自己的需求进行调整。请确保已经连接到Mongo数据库,并且通过Mongoose配置了正确的连接字符串。