节点-无效的select()参数。必须为字符串或对象

时间:2018-08-08 20:20:40

标签: node.js express mongoose async-await cloudinary

我正在创建一个网站,用户可以在其中编辑已有的帖子,并将自己的图像添加到该帖子中。但是,上传任何图像时都会收到错误消息。我正在使用Node,Express,Mongoose和Cloudinary完成此任务。

这是用户填写的编辑表单:

<div class="row">
    <h1 style="text-align: center">Upload photos for: <%= listing.address %></h1>
    <div style="width: 30%; margin: 25px auto;">
        <form action="/<%= listing._id %>/dashboard?_method=PUT" method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label for="image">Images</label>
                <input type="file" id="images" name="listing[images]" accept="image/*" multiple required>
            </div>
            <div class="form-group">
                <button class="btn btn-lg btn-primary btn-block">Submit!</button>
            </div>
        </form>
        <a href="/">Go Back</a>
    </div>
</div>

以下是上传图片和更新Mongoose模型的PUT路线:

//submit photos
router.put("/:id/dashboard", isLoggedIn, async function(req, res){
  Listing.findById(req.params.id, upload.array("listing[images]"), async function(err, foundListing){
    req.body.listing.images = req.body.listing.images || [];
    for (const file of req.files) {
        let result = await cloudinary.uploader.upload(file.path);
        req.body.listing.images.push(result.secure_url);
    }
    res.redirect("/");
  });
});

这是我尝试上传图片时收到的错误:

(node:8048) UnhandledPromiseRejectionWarning: TypeError: Invalid select() argument. Must be string or object.
(node:8048) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8048) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

在“列表”猫鼬模型中,我有一个名称为“ images”的字符串数组,用于存储上传的图像URL。任何帮助将不胜感激。预先感谢。

1 个答案:

答案 0 :(得分:0)

下面是findByID的参数:

  1. 要查询的_id的
  2. id«Object | String | Number»值
  3. 要返回的[投影]«对象|字符串»可选字段,请参见Query.prototype.select()
  4. [选项]«对象»可选,请参见Query.prototype.setOptions()
  5. [回调]«功能»

这就是为什么当您传递既不是对象也不是字符串的TypeError: Invalid select() argument. Must be string or object.时给出upload.array("listing[images]"的原因。另外,findByID只会返回文档,并且不会像您尝试的那样进行更新。您将需要findByIdAndUpdate来更新文档。