【发布时间】:2021-11-16 18:56:12
【问题描述】:
我是 Mongodb 的新手,当我尝试使用 push 方法将对象数组推送到 mongodb 时遇到打字错误。为此,我正在使用包装器 mongdb 服务。
public saveRental = () => {
return this.connector
.connect()
.then(() => {
return this.connector.update(
"polcyData", // collection name
{ _id: "dummyid" },
{ "$push": { "myArray": { "field1": "abc", "field2": "def" } } },
);
});
};
这是我在悬停 $push 方法时遇到的错误:
(property) $push?: PushOperator<any> | undefined
Type '{ myArray: { field1: string; field2: string; }; }' is not assignable to type 'PushOperator<any>'.
Type '{ myArray: { field1: string; field2: string; }; }' is not assignable to type 'NotAcceptedFields<any, any[]>'.
Property 'myArray' is incompatible with index signature.
Type '{ field1: string; field2: string; }' is not assignable to type 'undefined'.ts(2322)
index.d.ts(1256, 5): The expected type comes from property '$push' which is declared here on type 'UpdateQuery<any>'
这是更新方法参数:
update(collectionName: string, filter: MongoClient.FilterQuery<any>, update: MongoClient.UpdateQuery<any>, options?: MongoClient.UpdateOneOptions): Promise<any>;
这是 UpdateQuery 类型
/** https://docs.mongodb.com/manual/reference/operator/update */
export type UpdateQuery<TSchema> = {
/** https://docs.mongodb.com/manual/reference/operator/update-field/ */
$currentDate?: OnlyFieldsOfType<TSchema, Date, true | { $type: 'date' | 'timestamp' }>;
$inc?: OnlyFieldsOfType<TSchema, number>;
$min?: MatchKeysAndValues<TSchema>;
$max?: MatchKeysAndValues<TSchema>;
$mul?: OnlyFieldsOfType<TSchema, number>;
$rename?: { [key: string]: string };
$set?: MatchKeysAndValues<TSchema>;
$setOnInsert?: MatchKeysAndValues<TSchema>;
$unset?: OnlyFieldsOfType<TSchema, any, ''>;
/** https://docs.mongodb.com/manual/reference/operator/update-array/ */
$addToSet?: SetFields<TSchema>;
$pop?: OnlyFieldsOfType<TSchema, any[], 1 | -1>;
$pull?: PullOperator<TSchema>;
$push?: PushOperator<TSchema>;
$pullAll?: PullAllOperator<TSchema>;
/** https://docs.mongodb.com/manual/reference/operator/update-bitwise/ */
$bit?: {
[key: string]: { [key in 'and' | 'or' | 'xor']?: number };
};
};
谁能帮我解决这个问题?任何帮助将非常感激。该错误仅适用于更新数组运算符: https://docs.mongodb.com/manual/reference/operator/update-array
【问题讨论】:
-
你试过了吗:{ "myArray": { "$push": { "field1": "abc", "field2": "def" } } },
-
@matthPen 是,但仍然出现错误:参数类型 '{ myArray: { $push: { field1: string;字段2:字符串; }; }; }' 不可分配给“UpdateQuery
”类型的参数。对象字面量只能指定已知属性,并且 'myArray' 不存在于类型 'UpdateQuery ' 中。 -
{$set:{ "myArray": { "$push": { "field1": "abc", "field2": "def" } } }} ?
-
@matthPen 这次打字稿错误,但我无法保存它的抛出错误:“'myArray.$push' 中的美元 ($) 前缀字段 '$push' 对存储。”
标签: javascript node.js mongodb typescript mongodb-query