【问题标题】:How to use default url for image in mongoose?如何在猫鼬中使用默认网址作为图像?
【发布时间】:2020-09-04 04:52:05
【问题描述】:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var url = "https://i.stack.imgur.com/34AD2.jpg";
var UserSChema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    email: String,
    profilePic: {type: String, default: url},
    username: String,
    password: String,
    isAdmin: {type: Boolean, default: false}
});

UserSChema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSChema);

上面提到的是我的代码,我尝试将字符串设置为 url 并使用它,但它不起作用。每当我去检查 mongo shell 中的值时,profilePic 将为空。

【问题讨论】:

  • 你为什么要添加网址?
  • 只需输入字符串,然后使用multer上传即可。

标签: mongodb express mongoose mongoose-schema


【解决方案1】:

如果您的 mongo 集合中已经有文档,它将不会在数据库中为它们更新图像 URL,它会在您保存任何新数据时添加默认 URL,如果您使用 mongoose 也会添加旧记录找到他们。

因此,在使用 mongoose 时,您将始终在代码中获得默认值 https://i.stack.imgur.com/34AD2.jpg,但如果在 mongo shell 中看到旧文档的 profilePic 将为空。

如果您还想更新所有旧文档中 profilePic 的默认值,请在 Mongo 控制台中运行以下查询。

db.getCollection('users').updateMany({},{$set:{"profilePic": "https://i.stack.imgur.com/34AD2.jpg"}})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-01
    • 2015-02-26
    • 2018-07-05
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    相关资源
    最近更新 更多